https://kotlinlang.org logo
Title
d

David Cuesta

02/27/2019, 8:25 AM
Hi guys, question about coroutines. Anyone knows why testList works and testMap launches an error when calling the suspend function?
import kotlinx.coroutines.delay

suspend fun first(a: Int): Int {
    delay(100)
    return a + 1
}

suspend fun testMap(a: Map<String, Int>): Int {

    a.forEach { key, value ->
        first(value)
        println(value)
    }

    return 0
}

suspend fun testList(a: List<Int>): Int {

    a.forEach {
        first(it)
        println(it)
    }

    return 0
}
g

gildor

02/27/2019, 8:26 AM
What is exactly doesn’t work?
ahh
I see
Replace
forEach { key, value ->
with
forEach { (key, value) ->
first is a method of Java’s List interface on Java 8 (lambda with 2 arguments), second is Kotlin inline extension function (lambda with 1 Map.Entity<K,V> argument + destructuring)
First doesn’t allow call suspend functions, second does because this extension is inlined (and you can call suspend function from inline function that called in suspend lambda)
👍 4
d

David Cuesta

02/27/2019, 8:30 AM
@gildor lot of thanks for the explanation, it is clear now. Thank you for answering so quickly too.