Is it possible to typecast to satisfy multiple type constraints in kotlin?
Say I have the following case, but want to avoid type casting to class C (in case multiple classes implement A and B, or I don't know type C):
interface A
interface B
class C: A, B
fun <T> foo(bar: T) where T: A, T: B {
}
Is it possible to typecast to A and B simultaneously? Smart cast doesn't seem to allow this. Can I manually cast somehow?
val c = C()
foo(c) // works
val d: Any = c
if (d is A && d is B) {
foo(d) // smart cast doesn't work here, compiler error
}
// Something like this maybe?
foo(d as A && B)
I know it's possible by creating a new interface that inherits from both A and B, and then use that, but that may not be possible if I don't control the classes in question.
Thanks
The type has to explicitly implement the required interfaces and since Any cannot be both B and A (even though it implements both) simultaneously there has to be a third type, like C.
This similar question has a generic work around; Is intersection casting possible in Kotlin?
so arbitrary types T which implement A and B can be recognized as such but is and as can't be directly composed with && which makes it impossible to satisfy your functions type constraints without some kind of explicitly implementing wrapper.