Hi, is it possible to cast to two interfaces at th...
# announcements
o
Hi, is it possible to cast to two interfaces at the same time... without having "combining" interface Like cast some object to Comparable and CharArray at the same type, so function of shape fun <T> doStuff(param:T) where T : Comparable, T : CharArray can use the cast object?
s
If you can somehow make an unchecked cast to a combining interface then I guess it would work
Maybe a bit fragile xD
o
But I don't want to introduce combining interface
m
You can kinda simulate Java-style casting to an interface intersection type via the following smart casting trick:
Copy code
interface A
interface B

fun foo(a: Any) {
    a as A
    a as B
    bar(a)
}

fun <T> bar(t: T) where T : A, T : B {}
UPD: However, in most cases you can achieve the same thing in a safer fashion with
if (a is A) ... if (a is B)
chain, as smart casts support such a case as well
o
Copy code
interface Interface1 {
    val v1:String
}

interface Interface2 {
    val v2:Int
}

class ExperimentalClass : Interface1, Interface2 {
    override val v1 : String = "ABC"
    override val v2 : Int = 42
}

fun <T> printStuff(value:T) where T : Interface1, T:Interface2 {
    println(value.v1)
    println(value.v2)
}

fun doSomething(obj:Any) {
    // if (obj is Interface2 && obj is Interface1) printStuff(obj)
    obj as Interface2
    obj as Interface1
    printStuff(obj)
}

fun main() {
    val e = ExperimentalClass()
    doSomething(e)
}
Does not compiles, though does not show any red errors in IntelliJ
m
Which Kotlin version are you using? And this example may need you to switch to the new inference via
-Xnew-inference
o
1.3.40
m
Your snippet works on my machine with the
-Xnew-inference
and 1.3.40; consequently, IDEA does not show any errors exactly because it switched to the new inference engine under the hood some time ago 😃
o
Yes, did the change, and it works. Thanks Unfortunately won't be able to use in real production project, which runs on Kotlin 1.2.x, so no luch there 😞
😢 1