Home > Blockchain >  Strange behaviour of lambdas that return `dynamic` in Kotlin/JS interop
Strange behaviour of lambdas that return `dynamic` in Kotlin/JS interop

Time:11-25

I want to write a lambda function that returns dynamic that ends with an assignment operation. The following does not type-check:

var a: Int?
val f: () -> dynamic = {
    a = 42
}

Note: this example is somewhat artificial for the purposes of making it minimal. In reality, I need to assign this lambda to XMLHttpRequest.onreadystatechange, hence the type requirement.

f has type () -> Unit when the type annotation is removed. Why cannot () -> Unit be cast to () -> dynamic?

Moreover, how come this example type-checks?

val f2: () -> dynamic = {
    print("foo")
}

f2 without the annotation also has the type () -> Unit. Why does f2 type-check and f doesn't?

Finally, what is the appropriate way to write f? Add a Unit or null at the end, perhaps? That works but looks rather ugly. Is there a better way to do that?

CodePudding user response:

I'm sure you can find an answer here, because your problem looks similar to this topic

  • Related