
Hey android developers! Are you using Kotlin for your android projects? Or, are you just about to stop using java and use Kotlin for your android projects? Okay, Anyway, whatever the reason is, you are here which means you are trying to learn Kotlin scope functions. So just stick with me guys and we will discuss what the heck is this Kotlin scope function and how you can use this scope function to write awesome concise code for whatever project you are working on. So, let me start the show man.
So, what exactly this scope function is?
When you use the scope function then it forms a temporary scope. In this scope, you can access the object without its name. There are five scope functions: let, run, with, apply, and also.
Confused?
You know I’m a mind reader. I know what you are thinking. you are like, where the heck is the example, give me an example.
So let’s move on to the example.
Let’s consider a class Person –
data class Person(var name: String, var age: Int, var city: String) {
fun moveTo(newCity: String) { city = newCity }
fun incrementAge() { age++ }
}
fun main() {
Person("Alice", 20, "Amsterdam").let {
println(it)
it.moveTo("London")
it.incrementAge()
println(it)
}
}
Just think about this. How would you write the above code without using the scope function let? You would introduce a new variable and repeat its name whenever you use it. Right?. But with the kotlin scope function, you don’t have to do all this. You can simply use it to refer to the object. That’s it.
Now that you have a clear understanding of the scope function you can explore all the other scope functions here – https://kotlinlang.org/docs/scope-functions.html
Leave a Reply