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 (?
).