[Kotlin] When to add () and when not to
Kotlin to not and add when
2023-09-14 08:59:13 时间
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 学习笔记(三)
- To add browser notifications to an online customer support live chat service system - gofly - self h
- kotlin获取属性注解
- 开心档-Kotlin 基础语法
- 【Kotlin】Kotlin 抽象类与接口 ( 接口声明 | 接口实现 | 抽象类声明与实现 )
- 【Kotlin】Kotlin 中使用 ButterKnife ( 仅用于适配 Kotlin 语言 | 不推荐新项目使用 )
- 重新构想前端开发!Kotlin 推出新功能:无需同时了解 Kotlin 和 JavaScript
- 【Kotlin 协程】协程的挂起和恢复 ② ( 协程挂起 和 线程阻塞 对比 )
- 【Kotlin 协程】Flow 异步流 ④ ( 流的构建器函数 | flow 构建器函数 | flowOf 构建器函数 | asFlow 构建器函数 )
- 【Kotlin】函数 ⑤ ( 匿名函数变量类型推断 | 匿名函数参数类型自动推断 | 匿名函数又称为 Lambda 表达式 )
- 【Kotlin】集合操作 ① ( List 创建与元素获取 | 安全获取集合元素 | getOrElse | getOrNull )
- 【Kotlin】扩展函数 ② ( 扩展属性 | 为可空类型定义扩展函数 | 使用 infix 关键字修饰单个参数扩展函数的简略写法 )
- 【Kotlin】函数式编程 ③ ( 早集合与惰性集合 | 惰性集合-序列 | generateSequence 序列创建函数 | 序列代码示例 | take 扩展函数分析 )