I have this piece of code and I’m wondering if thi...
# announcements
s
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:
Copy code
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
)?
m
You have to use
@OverloadResolutionByLambdaReturnType
for whatever reason. https://youtrack.jetbrains.com/issue/KT-38962#focus=Comments-27-4181061.0-0
n
til
2️⃣ 1
s
Thank you!