https://kotlinlang.org logo
o

Olekss

01/10/2020, 10:31 AM
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

spand

01/10/2020, 10:36 AM
If you can somehow make an unchecked cast to a combining interface then I guess it would work
Maybe a bit fragile xD
o

Olekss

01/10/2020, 10:42 AM
But I don't want to introduce combining interface
m

Marat Akhin

01/10/2020, 10:42 AM
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

Olekss

01/10/2020, 10:45 AM
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

Marat Akhin

01/10/2020, 10:47 AM
Which Kotlin version are you using? And this example may need you to switch to the new inference via
-Xnew-inference
o

Olekss

01/10/2020, 10:49 AM
1.3.40
m

Marat Akhin

01/10/2020, 10:52 AM
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

Olekss

01/10/2020, 10:55 AM
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
7 Views