dephinera
02/02/2021, 11:58 AMwhen
like the ones in Swift?
let point = CGPoint(x: 7, y: 0)
switch (point.x, point.y) {
case (0,0): print("On the origin!")
case (0,_): print("x=0: on Y-axis!")
case (_,0): print("y=0: on X-axis!")
case (let x, let y) where x == y: print("On y=x")
default: print("Quite a random point here.")
}
AFAIK Swift language supports tuples and I suppose the construct here does a tuple comparison, but I don't see a reason why this shouldn't be just a syntax sugar for multiple if-elses or a when without a parameter and comparisons in each branch. One thing that I think might be an issue is if we want to match types, where we'd have something like this:
sealed class A {
class X : A()
class Y : A()
}
sealed class B {
class X : B()
class Y : B()
}
And then I guess there should be more syntax introduced, like this
...
fun foo(a: A, b: B) = when (a, b) {
(is A.X, is B.X) -> TODO()
(is A.Y, is B.Y) -> TODO()
}
Or if we want to match multiple types
...
fun foo(a: A, b: B) = when (a, b) {
(is A.X or is A.Y, is B.X) -> TODO()
(is A.Y or is A.X, is B.Y) -> TODO()
}
// or
fun foo(a: A, b: B) = when (a, b) {
(is (A.X | is A.Y), is B.X) -> TODO()
(is (A.Y | is A.X), is B.Y) -> TODO()
}
I hope I explained the idea well enough. So are there any limitations to make this possible? If not - should we expect something like this in the future? Do you think it's something that we actually need?raulraja
02/02/2021, 12:38 PMA | B
this would also require to port the kind of intersection types that polymorphic functions with bounds like <A : Comparable<A>> support since the APIs intersected need to be accesible in the right hand side of the match block.
I’m not seeing much interest in bringing advanced pattern matching to Kotlin but I believe the kinds of examples you showed there are technically possible at the risk of doing too much.
Another issue is that there not seems to be active development in having compiler plugins to be transparently supported by the kotlin IDEA plugin at the moment. This kind of support would also require for the user to install an independent plugin which I think it’s too much to ask of users just to get a lang feature but i also wish this changed and we got better pattern matching.