Completed Coursera: Kotlin for developers course
This commit is contained in:
35
src/Lambdas.kt
Normal file
35
src/Lambdas.kt
Normal file
@ -0,0 +1,35 @@
|
||||
fun main() {
|
||||
listOf(1, 2, 3)
|
||||
// Lambda, it is inferred argument, only used for single argument lambdas
|
||||
.filter { it % 2 == 0 }
|
||||
// Explicitly define args
|
||||
.map { value -> value * value }
|
||||
|
||||
mapOf(1 to 2)
|
||||
// Automatic destructuring of mep entries
|
||||
.mapValues { (key, value) -> "$key $value" }
|
||||
}
|
||||
|
||||
fun returnFromLambda(): List<Int> {
|
||||
return listOf(3, 0, 5)
|
||||
.flatMap {
|
||||
if (it == 0) return emptyList() // Returns from the function, will always return an empty list when 0
|
||||
listOf(it, it)
|
||||
}
|
||||
}
|
||||
|
||||
fun returnFromLambda2(): List<Int> {
|
||||
return listOf(3, 0, 5)
|
||||
.flatMap {
|
||||
if (it == 0) return@flatMap emptyList() // Returns from the lambda
|
||||
listOf(it, it)
|
||||
}
|
||||
}
|
||||
|
||||
fun returnFromLambda3(): List<Int> {
|
||||
return listOf(3, 0, 5)
|
||||
.flatMap l@{ // Define custom label
|
||||
if (it == 0) return@l emptyList() // Returns from the lambda
|
||||
listOf(it, it)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user