I observe an interesting type inference behavior regarding
it
parameter in lambdas contained in pairs, lists or other data structures. This code sample
var pair: Pair<Int, (String) -> String> = 2 to { "param $it" }
var pair2: Pair<Int, (String) -> String> = 2 to { p -> "param $p" }
var list: List<(String) -> String> = listOf { "param $it" }
var list2: List<(String) -> String> = listOf { p -> "param $p" }
looks fine to IDE, but fails to compile with the following errors for the lines using
it
lambda parameter:
Type inference failed. Expected type mismatch: inferred type is Pair<Int, () -> String> but Pair<Int, (String) -> String> was expected
Unresolved reference: it
Type inference failed. Expected type mismatch: inferred type is List<() -> String> but List<(String) -> String> was expected
Unresolved reference: it
But the compiler is happy with the root-level lambda declarations like this
var func: (String) -> String = { "param $it" }
var func2: (String) -> String = { p -> "param $p" }
Is this a bug or an intended behavior? Are there any workarounds that would make the compiler happy and at the same time keep the code neat (that is, using
it
but without full lambda type annotations at usage site)?
I'm using Kotlin 1.3.71 in multiplatform project and can see this both in JVM and JS targets.