[Kotlin] When to add () and when not to

Let's see following code:

    println(colors.reduce {
        acc, curr -> "$acc, $curr"
    }) // red, blue, green, black

    val myMap = mapOf(1 to "one", 2 to "two", 3 to "three")
    myMap.filter {(k, v) -> v.startsWith("t")}.forEach {(k,v) -> println("$k $v")}

 

Why in "reduce" we don't need to add ()

but in "filter" example we need?

 

Answer is in "reduce" it is a function take two params, which doesn't require ()

in "filter" it means destructing, in fact, you can write:

myMap.filter { item -> item.value.startsWith("t")}.forEach {item -> println("${item.key} ${item.value}")}

 

posted @ 2020-10-26 16:22  Zhentiw  阅读(107)  评论(0编辑  收藏  举报