In this article, We are going to learn how to use scoped functions in kotlin programming language using some examples.
There are five scoped functions in kotlin: let, run, with, also, apply.
let function returns the result of expression. Variables can not be used outside if they are declared inside the expression.
it keyword refers the variable inside let. We can also renamed it to readable lambda argument.
let is also used with question mark to check value is null or not when obtaining a result. It is the most used scoped function in kotlin. If we use let then we do not need to check value is null or not with if loop.
run is similar to let function but the difference is this keyword is used to refer variable instead of it. The other difference is we can not renamed this to readable variable.
run function can also be used to initialize variable and return the result.
with is used to change value of variable without need to call dot operator every time. in with function, this keyword is used to refer the variable like run function. But for null safety, use of with function is difficult.
also function is used to do some additional processing. also function uses it keyword to refer variable like let. But also function returns original value instead of any new value.
apply function is same as run function in terms of refer variable by this keyword. But the difference is apply function does not accept any return statement.