I have this piece of code and I’m wondering if this is a bug or just not possible (as designed) for the type inference of Kotlin.
Here is a snippet:
class MyList<T> {
@JvmName("flatMapList")
fun <R> flatMapList(block: Function1<T, List<R>>): MyList<R> = TODO()
@JvmName("flatMapListPair")
fun <R> flatMapList(block: Function1<T, Pair<R, R>>): MyList<R> = TODO()
@JvmName("flatMapList2")
fun <R> flatMapList2(block: (T) -> List<R>): MyList<R> = TODO()
@JvmName("flatMapListPair2")
fun <R> flatMapList2(block: (T) -> Pair<R, R>): MyList<R> = TODO()
}
fun test() {
val x = { it: Int -> Pair("1", "2") }
val y = { it: Int -> listOf("1", "2") }
MyList<Int>().flatMapList(x) // OK
MyList<Int>().flatMapList({ it: Int -> Pair(1, 2) }) // ERROR
MyList<Int>().flatMapList2(x) // OK
MyList<Int>().flatMapList2({ it: Int -> Pair(1, 2) }) // ERROR
MyList<Int>().flatMapList(y) // OK
MyList<Int>().flatMapList({ it: Int -> Pair(1, 2) }) // ERROR
MyList<Int>().flatMapList2(y) // OK
MyList<Int>().flatMapList2({ it: Int -> Pair(1, 2) }) // ERROR
}
Why does the compiler (and IDE) generate an error when directly assigning the lambda, but it compiles fine when using a temporary variable (
x
and
y
)?