Is intersection casting possible in Kotlin?
Kotlin does not support intersection types. This causes variable
to be smart cast to Any
, because that is the common ancestor of A
and B
.
However, Kotlin does support generic type constraints. You can use this to constrain a type parameter to one or more types. This can be used on both methods and classes. This is the syntax for functions (the equivalent of your methodName
in Kotlin):
fun <T> methodName(arg: T)
where T : A,
T : B {
....
}
You can use this to get around your problem by creating a class which extends both A
and B
, and then delegates the implementation of these types to your object. Like this:
class AandB<T>(val t: T) : A by t, B by t
where T : A,
T : B
You can now call methodName
by changing your if-test to check if it is a AandB<*>
:
if (variable is AandB<*>) {
methodName(variable, ...)
}
You do need to wrap variable
in a AandB
somewhere though. I don't think you can do it if you don't have the type information for variable
available anywhere.
Note: The AandB
class does not implement hashCode
, equals
or toString
. You could implement them to delegate to t
's implementation.
Note 2: This only works if A
and B
are interfaces. You can not delegate to a class.