Empty subject in match and switch constructions
| From: | Dmitry Derepko | Date: | Sun, 02 Feb 2025 12:04:38 +0000 |
| Subject: | Empty subject in match and switch constructions | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-126266@lists.php.net to get a copy of this message | ||
Hi!
I’m thinking about making match (true) and switch (true) be more lightweight by removing the
subject “(true)” and making matching “true condition” by default.
So $var = match (true) { … } can be used as $var = match { … }.
It’s often used in Kotlin. Pretty convenient way to use combined conditions. It’s natively
understandable because there should be a condition:
$result = match {
$x < $n => …,
$x > $n => …,
else => …,
}
The same explanation for switch construction, but in Kotlin it’s the same construction
“when":
val result = when {
x < n -> …
x > n -> …
else -> …
}
var result = null
when {
x < n -> { result = … }
x > n -> { result = … }
else -> return
}
https://kotlinlang.org/docs/control-flow.html#when-expressions-and-statements
Conditions and loops
kotlinlang.org
when construction is overwhelming, but some features are totally handy, such as
checking for class of the subject:
when (obj) {
is Class1 -> …
is Class2 -> …
else -> ...
}
Which was implemented by Ilija Tovilo in: https://github.com/php/php-src/compare/master...iluuu1994:pattern-matching
By the way, what do you think about allowing to drop the subject of match / switch as a first
iteration?
Maybe would be better to ask Ilija to recreate his PR?
----------
Best regards,
Dmitrii Derepko.
@xepozz