Cannot infer type... Why?


#1

Hi! I converted my Java code to Kotlin and got uncompiled code. The example below:

class SomeClass (var callbackMessage: String){
    fun someMethod(callback: SomeCallback) {
        //do something
        callback.invoke(callbackMessage)
    }
}

interface SomeCallback {
    fun invoke(someString: String)
}

fun main(args: Array<String>) {
    val someInstance = SomeClass("abc")
    //uncompiled. reason: cannot infer type
    //someInstance.someMethod({someString -> println(someString)})
    //someInstance.someMethod({someString -> println(someString)} as SomeCallback)

    //compiled
    someInstance.someMethod({someString: String -> println(someString)} as SomeCallback)
}

#2

Your Java code relies on SAM conversion, which is currently not supported for classes defined in Kotlin (but may be supported later). The idiomatic solution for Kotlin 1.0 is to replace the SomeCallback interface with a function type: (String) -> Unit


#3

Despite this, if converter will generate for me
b.sameMethod({someString: String -> println(someString)} as SomeCallback)
instead
b.sameMethod({someString -> println(someString)})
After conversion, I’ll get compilable code and be happy.


#4

It compiles, but will not run. You will get something like java.lang.ClassCastException: $main$callback$1 cannot be cast to SomeCallback


#5

Well, tested, ok. You are right