不明白為什麼.count {it==true}可以簡寫成.count{it}

来源:5-6 案例:为 String 实现四则运算

蚊子叮死我了

2022-12-08

不明白为什么.count {it = = true}可以简写成.count{it},
因为这样传入的predicate的最后一行代码不就等价于return it
这样不会直接回传入参吗 似乎没有做逻辑判断?
但运行却是能实现判断的 实在搞不懂
这样我要如何理解别人的代码如果他只写.方法名{it}的话
我原本是理解为 return it ,现在需要改理解为 return it = = true吗?

写回答

1回答

bennyhuo

2022-12-08

it 本身就是 Boolean 类型,所以返回 it 和 返回 it == true 本身就是等价的。
0
1
蚊子叮死我了
好的我終於看明白了 .count{it},的全寫是.count{it - >it}, 於是在if (predicate(element))中的 predicate(element)會回傳it本身,也就是直接把element不做處理直接回傳 也就是Boolean,所以會變成if(element){count=count+1}, 總算是看明白了 public inline fun Iterable.count(predicate: (T) -> Boolean): Int { if (this is Collection && isEmpty()) return 0 var count = 0 for (element in this) if (predicate(element)) checkCountOverflow(++count) return count }
2022-12-11
共1条回复

学会Kotlin 突破开发语言瓶颈

如果有一门语言可以取代Java,那么它一定是Kotlin。

1760 学习 · 481 问题

查看课程