Published on

Chaining Lets in Kotlin


Kotlin is excellent at helping you manage nulls.

It is designed so you can explicitly see whether or not an object is nullable and gives you the tools to handle this.

One trick I picked up today is using let to chain a bunch of nullable logic together but handle it safely.

For example say I have a regular expression where I want to extract year (yy), month (mm), day (dd) from a string with other characters following this. I then want to convert this to a date and finally run a check against this. Without let my code may look as follows:

val dateMatches = dateRegex.matchEntire(userInput)

val inputDate = if(dateMatches != null) {
    val (yy, mm, dd) = dateMatches.destructured
    convertStringsToLocalDate(yy, mm, dd)
} else {

val isBeforeToday = inputDate?.isBefore( ?: false

Using chained lets I can clean up the above as follows:

val isBeforeToday =
    ?.let { matches ->
        val (yy, mm, dd) = matches.destructured
        convertStringsToLocalDate(yy, mm, dd)
    ?.let { inputDate ->
    } ?: false