[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}")}
原文地址:https://www.cnblogs.com/Answer1215/p/13879118.html