Updated 28 February 2020
Kotlin Scope functions
The Kotlin standard library contains several functions that are used for executing a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. Here, we will check five of them:-
kotlin let:-
Kotlin let is a scoping function wherein the variables declared inside the expression cannot be used outside. let takes the object it is invoked upon as the parameter and returns the result of the lambda expression.
1 2 3 4 5 6 |
fun main(args: Array<String>) { var str = "Hello World" str.let { println("$it!!") } println(str) //Hello World } |
the key ‘it’ keyword contains a copy of the property inside let.
Kotlin run:-
Kotlin run is another interesting function. The following example demonstrates its use cases.
1 2 3 4 5 6 7 |
var tutorial = "This is Kotlin run scope function" println(tutorial) //This is Kotlin run scope function tutorial = run { val tutorial = "This is run function" tutorial } println(tutorial)//This is run function |
Kotlin also:-
As the name says, also expressions do some additional processing on the object it was invoked.
Unlike let, it returns the original object instead of any new return data. Hence the return data has always the same type.
Like let, also uses it too.
1 2 3 |
var m = 1 m = m.also { it + 1 }.also { it + 1 } println(m) //prints <span class="hljs-number">1</span> as it is returning it's original object. |
Kotlin apply:-
Kotlin apply is an extension function on a type. It runs on the object reference (also known as the receiver) into the expression and returns the object reference on completion.
1 2 3 4 5 |
data class Person(var name: String, var tutorial : String) var person = Person("XYZ", "Kotlin") person.apply { this.tutorial = "Swift" } println(person) |
Kotlin with:-
Like apply, this is used to change instance properties without the need to call dot operator over the reference every time.
1 2 3 4 5 6 7 8 9 |
data class Person(var name: String, var tutorial : String) var person = Person("XYZ", "Kotlin") with(person) { name = "ABC" tutorial = "Kotlin Scope Functions" } // now the person:- Person("ABC", "Kotlin Scope Functions") |
You can get more information regarding the scope functions and their uses in the following link:-
https://kotlinlang.org/docs/reference/scope-functions.html
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.