Published on

Chaining Lets in Kotlin

Authors

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 {
    null
}

val isBeforeToday = inputDate?.isBefore(LocalDate.now()) ?: false

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

val isBeforeToday =
    dateRegex.matchEntire(userInput)
    ?.let { matches ->
        val (yy, mm, dd) = matches.destructured
        convertStringsToLocalDate(yy, mm, dd)
    }
    ?.let { inputDate ->
        inputDate.isBefore(LocalDate.now())
    } ?: false