Completed Coursera: Kotlin for developers course

This commit is contained in:
Martin Berg Alstad
2025-07-30 14:34:03 +02:00
committed by Martin Berg Alstad
commit 64d9e4ada7
41 changed files with 608 additions and 0 deletions

35
src/Lambdas.kt Normal file
View 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)
}
}