首页 > 其他 > 详细

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

时间:2020-10-26 19:53:24      阅读:37      评论:0      收藏:0      [点我收藏+]

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}")}

 

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

原文:https://www.cnblogs.com/Answer1215/p/13879118.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!