Sam Stone
11/25/2022, 4:48 AMval Any.field
get() = when (this) { //these classes don't inherit a common ancestor that has the getField() method, so we need to parse them out into distinct classes
is Class1 -> field
is Class2 -> field
is Class3 -> field
...
else -> null? throw error?
}
A useful feature that would help this case is if I could specify that a function can only be called on certain types, similar to where
, so that the compiler knows that it is at least one of those classes, and can find the corresponding function or field. At the very least, it would write this out for me.wasyl
11/25/2022, 5:35 AMRoukanken
11/25/2022, 8:14 AMval (Class1 | Class2 | Class3).field
get() = when (this) {
is Class1 -> field
is Class2 -> field
is Class3 -> field
}
There is a ticket for that: https://youtrack.jetbrains.com/issue/KT-13108/Denotable-union-and-intersection-types
No idea if/when it'll get implemented, as it is a very complex feature.wasyl
11/25/2022, 8:18 AMextension interface Foo {
val someField: Int
}
class Class1 // no fields
class Class2 // no fields
extension Class1 : Foo {
val someField get() = field
}
extension Class2 : Foo {
val someField get() = field
}
then you can always cast Class1
, Class2
as Foo
even though the original declaration doesn’t implement it. That’d be moving the when
into the type system, but I see how an exhaustive when
on a union type is more aligned with the question 👍Kevin Del Castillo
11/29/2022, 2:27 PMwasyl
11/29/2022, 2:29 PM