Lambdas Recap
Let's recap and do an example in REPL. Restart REPL to start from a clean slate.
A lambda is an anonymous function, a function without a name.
{println("Hello People")}()
Hello People
We can assign lambda to a variable,waterFilter, with an argument, dirty, and do a calculation, dividing dirty by two, whose result will be returned. For example, here, we are passing 90 in waterFilter, and we get back 45.
waterFilter(90)
res5: kotlin.Int = 45
Now, here is a data class, Fish, that has one property, its name. We can then create a variable, myFish,
that is assigned to a list of Fish with three Fish each with a different name: Flipper, Moby Dick, and Dory.
To print the names of all the fish whose name contains the letter I, we do the following.
We start with our list of fish, myFish, then we add a filter. Inside the filter, we use it to refer to the current element of the list. We get the name and check whether it contains the letter "i".
This returns a list of all the names that contain the letter "i". Reapply joinToString to that returned list.
data class Fish(val name: String) val myFish = listOf(Fish("Flipper"), Fish("Moby Dick"), Fish("Dory")) myFish.filter{it.name.contains("i")} [Fish(name=Flipper), Fish(name=Moby Dick)]
JoinToString creates a string from all the names of the elements in the list separated using this applied separator, which is a space in our case, and returning that string. JoinToString is another one of those handy standard library functions, and there is a link in the notes.
data class Fish(val name: String)
val myFish = listOf(Fish("Flipper"), Fish("Moby Dick"), Fish("Dory"))
myFish.filter{it.name.contains("i")}.joinToString(" "){it.name}
Flipper Moby Dick
Helpful Links:
Lambdas
joinToString
Kotlin documentation
Kotlin Koans
Kotlin Standard Library
Comments
Post a Comment