Updated 31 January 2020
Kotlin Scope Functions are basically provided to manage the variable scopes easily. These are designed in a way that you can access the variables without even using their names again and again and also you don’t need to manage their scopes. You can definitely check the official doc.
Support, we have a class that has few variables in it.
1 |
open class StudentModel(val name: String, val age: String, val country: String) {} |
As you can see above. If I want to access the variable from this class then I would have to create its object and use its identifier. The below-given code will help you with that.
1 2 3 4 |
val studentModel = StudentModel("John", "27", "India") print(studentModel.name) print(studentModel.age) print(studentModel.country) |
As you can see we, again and again, writing the studentModel identifier to access each property.
Here the Kotlin Scope Functions come to rescue. Let’s see one by one each of them.
The object is represented by the argument (it). It returns the last statement of the lambda expression.
1 2 3 4 5 |
StudentModel("John", "27", "India").let { print(it.name) print(it.age) print(it.country) } |
The object is available as a receiver (this). It returns the last statement of the lambda expression.
1 2 3 4 5 |
with(StudentModel("John", "27", "India")) { print(name) print(age) print(country) } |
The object is available as a receiver (this). It returns the last statement of the lambda expression.
1 2 3 4 5 |
StudentModel("John", "27", "India").run { print(name) print(age) print(country) } |
You can execute several statements with the run.
1 2 3 4 5 6 7 |
val studentModel = run { val name = "John" val age = "27" val country = "India" StudentModel(name, age, country) } |
The object is available as a receiver (this). It returns the object itself.
1 2 3 4 |
val studentModel = StudentModel("John", "", "").apply { age = "27" country = "India" } |
The object is available as an argument (it). It returns the object itself.
1 2 3 4 |
val studentModel = StudentModel("John", "", "").also { it.age = "27" it.country = "India" } |
And the main feature of all of these functions is that you don’t need to think about the object that has been created. The will be automatically destroyed as soon as the scope function completes.
That’s all for this blog. Thank you very much. This is Vedesh Kumar signing off.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.