Cannot infer type... Why?


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

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)

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


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


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


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


Well, tested, ok. You are right