Scope Functions in Kotlin
Whole purpose of scope function is to execute block of code in the context of the object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope.
The above definition is a little complex right? But Kotlin is basically for simplifying and improving the readability. So we will check how scope function is doing the above in kotlin.
There are 5 types of Scope Function
- let
- apply
- also
- run
- with
1.let
Mostly used for null checks. When let is used with ?. we can safely access the object inside the scope function which won’t be null.
var city:String = "Newyork"
city?.let{
print("cityname length is ${it.length}")
}
In the above example, variable city’s length can be used with let and ?.
as you can see let is Referenced by let.
let returns the last statement
2.apply
When you want to initialize an object and want to set some properties, you have to set them like below
var imageView:ImageView =findViewById(R.id.imageView1)
imageView.visibility =View.VISIBLE
imageView.focusable = View.FOCUSABLE
imageView.scaleType =ScaleType.CENTER_CROP
this can be simplified by using apply.
imageView.apply {
visibility =View.VISIBLE
focusable =View.FOCUSABLE
scaleType = ImageView.ScaleType.CENTER_CROP
}
apply is referenced by this and returns the same object.
3.also
So with the above apply example, we need to add some logs also. With also, we can handle it without changing the apply.
imageView.apply {
visibility =View.VISIBLE
focusable =View.FOCUSABLE
scaleType = ImageView.ScaleType.CENTER_CROP
}.also{
print(imageView.getId())
}
When you see also
in the code, you can read it as “and also do the following with the object.”
Also is used to improve the readabilty mainly.
It is referenced by it and returns the same object
4. run
run is the only scope function that has two variants
- run as an extension
run does the same as apply but invokes as let. That mean run do some changes on an object and returns the last statement
So it is useful when you and need to run certain operations over an object, and finally return one last operation, like the example below
val message = StringBuilder()
message.run{
append("City name is")
append("Newyork")
length
}
2. run as a function
Reduce the scope of certain variables, to avoid unnecessary access.
var isUserNameValid = userName.run{
isUserValid(userName)
}
run referenced by this and returns last statement
5.with
with is similar to apply and used less because it wont allow null check,while apply does
When you want to do multiple operation on an object ,with can be used
var webView =Webview(this)
with(webView){
settings.javaScriptEnabled =true
loadUrl("www.google.com")
}
Another use case for with
is introducing a helper object whose properties or functions will be used for calculating a value.
val numbers = mutableListOf("one", "two", "three")
val firstAndLast = with(numbers) {
"The first element is ${first()}," +
" the last element is ${last()}"
}
println(firstAndLast)
That’s all for now.
Happy Reading …. Happy Coding …