美文网首页Kotlin从入门到放弃Kotlin学习日记Kotlin
{Kotlin学习日记}Day21 Koan第五关

{Kotlin学习日记}Day21 Koan第五关

作者: William李梓峰 | 来源:发表于2017-07-28 13:54 被阅读48次

大家好,我是William。今天是Koan第五关,Lambdas,拉姆达。

https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Lambdas/Task.kt
上面是闯关链接。

Introduction

Lambdas

Kotlin supports a functional style of programming.
Read about higher-order functions and function literals (lambdas) in Kotlin.
Pass a lambda to any function to check if the collection contains an even number.
The function any gets a predicate as an argument and returns true if there is at least one element satisfying the predicate.

解:
Kotlin可以玩得起函数式编程,如果不熟悉Lambda,就先看看上面的链接,any是collection的标准函数,需要传递一个lambda表达式进去,返回布尔值。本题要求你编写一个检查是否包含偶数的lambda表达式。

答:
我喜欢用求余的方式来判定是否偶数。判定方式其实是不限的。

fun containsEven(collection: Collection<Int>): Boolean = collection.any { x -> x%2==0 }

小结

这里的lambda跟Java的有点不一样,起码多了一个大括号包含着,而且添加了很多机制,比Java要丰富很多。

相关文章

网友评论

    本文标题:{Kotlin学习日记}Day21 Koan第五关

    本文链接:https://www.haomeiwen.com/subject/yvnxlxtx.html