Published on

Playing Around Some More With Kotlins Let

Authors

Today I found additional opportunities to use let.

Another way to look at let is as the equivalent of the map operator on collections but for everything.

You can use let to transform a collection or a none-collection into something else. This is also useful if you want to convert your smaller methods into expression bodies if you chain lets together.

Pretend we want to convert a word to a number, repeat the word that many times and capitalize it. I intentionally split the capitalize step out just to demonstrate how this works but this gives a feel for it:

val wordToNumber = mapOf(
    "one" to 1,
    "two" to 2,
    "three" to 3
)

fun repeatNumberWord(numberWord: String): String = wordToNumber[numberWord]
    ?.let { number ->
        numberWord.repeat(number)
    }?.let { repeated ->
        repeated.capitalize()
    }
    ?: numberWord.capitalize()

In the above, I safely deal with scenarios where a word is not in our map and chain it together to get what I want using multiple lets. As I am using a let chain I can convert the method to its expression form.