Should this be part of the language? ```val Any.fi...
# language-evolution
s
Should this be part of the language?
Copy code
val 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.
w
Looks like extension interfaces? There's an open issue for that feature
r
I think he's more looking for union types eg something like:
Copy code
val (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.
w
I was thinking original idea is more like
Copy code
extension 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 👍
k
Hey @wasyl could you share the link to the issue?
w
I actually can’t find an active one, there’s https://youtrack.jetbrains.com/issue/KT-10468 which is stated to be a first step in supporting extension interfaces use cases (https://github.com/Kotlin/KEEP/pull/87#issuecomment-746042751). Other than that there’s https://youtrack.jetbrains.com/issue/KT-40900/support-extension-interfaces but it seems abandoned