Discovering basic scoping functions – let, also, apply
In this recipe, we are going to explore three useful extension functions from the standard library—let
, also
, and apply
. They work great together with lambda expressions and help to write clean and safe code. We are going to practice their usage while applying them to implement a sequence of data-processing operations.
Getting ready
Let's assume we can fetch the date using the following function:
fun getPlayers(): List<Player>?
Here, the Player
class is defined like this:
data class Player(val name: String, val bestScore: Int)
We would like to perform the following sequence of operations to the getPlayers()
function result:
- Print the original set of players in the list to the console
- Sort the collection of the
Player
objects in descending order - Transform collection
Player
objects into the list of strings obtained from thePlayer.name
property - Limit the collection to the first element and print it to the console
In order to accomplish the...