Search code examples
kotlinlet

Understanding the need for Kotlin let


I'm trying to understand why let is needed. In the example below I have a class Test with a function giveMeFive:

public class Test() {
    fun giveMeFive(): Int {
        return 5
    }
}

Given the following code:

var test: Test? = Test()

var x: Int? = test?.giveMeFive()

test = null

x = test?.giveMeFive()
x = test?.let {it.giveMeFive()}

x gets set to 5, then after test is set to null, calling either of the following statements return null for x. Given that calling a method on a null reference skips the call and sets x to null, why would I ever need to use let? Are some cases where just ?. won't work and let is required?

Further, if the function being called doesn't return anything, then ?. will skip the call and I don't need ?.let there either.


Solution

  • let()

    fun <T, R> T.let(f: (T) -> R): R = f(this)
    

    let() is a scoping function: use it whenever you want to define a variable for a specific scope of your code but not beyond. It’s extremely useful to keep your code nicely self-contained so that you don’t have variables “leaking out”: being accessible past the point where they should be.

    DbConnection.getConnection().let { connection ->
    }
    

    // connection is no longer visible here

    let() can also be used as an alternative to testing against null:

    val map : Map<String, Config> = ...
    val config = map[key]
    // config is a "Config?"
    config?.let {
    // This whole block will not be executed if "config" is null.
    // Additionally, "it" has now been cast to a "Config" (no 
    question mark)
    }
    

    A simple go to chart when to use when.