Use let or also to simplify working with nullable objects

suggest change

let in Kotlin creates a local binding from the object it was called upon. Example:

val str = "foo"
str.let {
    println(it) // it
}

This will print "foo" and will return Unit.

The difference between let and also is that you can return any value from a let block. also in the other hand will always reutrn Unit.

Now why this is useful, you ask? Because if you call a method which can return null and you want to run some code only when that return value is not null you can use let or also like this:

val str: String? = someFun()
str?.let {
    println(it)
}

This piece of code will only run the let block when str is not null. Note the null safety operator (?).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents