Description
Kotlin supports a functional style of programming. Read about higher-order functions and function literals (lambdas) in Kotlin.
Pass a lambda to
anyfunction to check if the collection contains an even number. The functionanygets a predicate as an argument and returns true if there is at least one element satisfying the predicate.
Kotlinは、関数型プログラミングをサポートしています。Kotlinの 高階関数と関数リテラル(ラムダ) を読んでください。
ラムダを
any関数に渡し、コレクションに偶数が含まれているかをチェックしてください。any関数はpredicate(boolを返す関数)を引数に取り、predicateを満たす要素が少なくとも1つ存在する場合にtrueを返します。
Code
fun containsEven(collection: Collection<Int>): Boolean = collection.any { value: Int -> value % 2 == 0 }
Memo
- ラムダ式のパラメータが1つである場合、
->を省略してitという名前で暗黙的に宣言できる。
fun containsEven(collection: Collection<Int>): Boolean = collection.any { it % 2 == 0 }
Javaでは、Java8から実装されたラムダ式。 Kotlinではこんなふうに書くよ、という内容でした。