[Kotlin 1.4] Suspend conversion on callable references is supported

atsuko

Atsuko Fukui

Posted on January 9, 2021

[Kotlin 1.4] Suspend conversion on callable references is supported

From Kotlin 1.4, suspend conversion on callable references is supported 🎉 Release note doesn't say much about this feature but it's really helpful when you use Flow#combine().

Let's pretend you want to combine two flows and use them in collect(). Before Kotlin 1.4, you may write code like this:

suspend fun before4_1() {
    combine(
        flowA, flowB
    ) { a, b ->
        a to b
    }.collect {
        val a = it.first
        val b = it.second
        println("$a and $b")
    }
}

val flowA = flowOf(1, 2)
val flowB = flowOf(3, 4)
Enter fullscreen mode Exit fullscreen mode

This code is kind of redundant and doesn't look great (too much as and bs! 😩)

From Kotlin 1.4, you can simplify the above code.

suspend fun from1_4() {
    combine(
        flowA, flowB, ::Pair
    ).collect { (a: Int, b: Int) ->
        println("$a and $b")
    }
}

val flowA = flowOf(1, 2)
val flowB = flowOf(3, 4)
Enter fullscreen mode Exit fullscreen mode

Before Kotlin 1.4, this code causes compile error because the type of the 3rd parameter of combine() is suspend function. Pair class constructor is not a suspend function so compile error will occur. From Kotlin 1.4, this 3rd parameter lambda will be converted to suspend function automatically and work fine.

Bounus: I use destructuring declarations for the parameter of collect().

    ).collect { (a: Int, b: Int) ->
Enter fullscreen mode Exit fullscreen mode

We can name values of pair.first and pair.second here. Type definition can be omitted but () is necessary.

💖 💪 🙅 🚩
atsuko
Atsuko Fukui

Posted on January 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related