More Kotlin Keywords
Learn about the let and this keywords and their differences in Kotlin.
We'll cover the following
The let
and this
keywords are two powerful tools in Kotlin that we can use to simplify and enhance our code. Let’s explore what these keywords are, how they work, and when to use them.
The let
keyword
The keyword let
is a scoping function in Kotlin that can perform operations on an object within a new scope. It takes the object it’s called on as its argument and returns the result of the lambda expression/action performed on that object. Its syntax is: object.let { lambda expression }
. Here, object
is the object we want to operate on, and the lambda expression is the code we want to execute on the object within the new scope.
One of the common use cases for the let
function is for null-checking. By using let
, we can ensure that we perform operations on an object if it’s not null
, avoiding potential null pointer exceptions.
Get hands-on with 1400+ tech skills courses.