Re: 'switch-expression' and the 'type guard' unary operator demo

From: Date: Sat, 19 Oct 2019 23:52:49 +0000
Subject: Re: 'switch-expression' and the 'type guard' unary operator demo
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-107581@lists.php.net to get a copy of this message
> On Oct 19, 2019, at 12:40 PM, Kosit Supanyo <webdevxp.com@gmail.com> wrote: > > Hi Internals > > I've just finished an implementation of 'switch-expression' that have been > discussed recently. So I would like to present my ideas here. This is great to see that you proactively implemented this. > The basic syntax of switch-expression in this implementation is: > > $result = switch ($expr) { > case $cond1 => $result1, > case $cond2 => $result2, > case $cond3 => $result3, > default => $default_result, > }; However, why the need to deviate with the existing syntax, making refactoring between switch statements and switch expressions more work that it needs to be. Is there some reason why keeping colons and semlicolons would not work? Given your syntax manually refactoring existing switches to use expressions, or refactoring back from expressions to statements will require more and tedious keystrokes than if you just kept colons and semicolons. Is there a strong reason to change to using fat arrows and colons? > You can omit parenthesized expression which is shortcut to switch > (true). > This change applies to switch statement as well. > > $v = switch { > case $x >= 0 && $x <= 100 => 1, > case $x >= 100 && $x <= 200 => 2, > default => 3, > }; > > switch { > case $x >= 0 && $x <= 100: > doSomething1(); > break; > case $x >= 100 && $x <= 200: > doSomething2(); > break; > default: > doNothing(); > break; > } I do very much like this innovation. Would love to see this work for switch statements too. > You can also use return and > throw in result expression. I recalled some > languages have this feature (but I've forgotten what language). This > feature can be very handy and useful in many use cases. > > $x = 'd'; > $v = switch ($x) { > case 'a' => 1, > case 'b' => 2, > case 'c' => return true, > default => throw new Exception("'$x' is not supported"), > }; What about break? > Additional feature in the demo patch is the 'type guard' unary operator > which is an operator that will perform type check on given value and throw > TypeError when type mismatch occurred, otherwise return the > value as is. > It has the same precedence as new. > > $a = 'This is a string'; > $v = <int>$a; // TypeError: Value is expected to be int, string given > > Just like type hints, can accept nullable types. > > $v = <?int>switch ($x) { > case 'a' => $result1, > case 'b' => $result2, > }; Nice! -Mike

« previous php.internals (#107581) next »