Android Kotlin Scope Functions

スポンサーリンク

Scope Functions

Scope Functions are block operations check null and execute some operations in block

This is the list of scope functions in kotlin

  • let
  • run
  • with
  • apply
  • also

let

null check scope, replacement of if – not null statement

In block, you can access object as “it”

val str : String? = null
str?.let {
   println("Not Null")
}
    
val empty = "test".let {   
    it.isEmpty()  // return
}
println(" is empty: $empty")

run

Similar with let, this is also scoping function In run block, we can skip this. (no need to use it)

var str : String? = null
str?.run {
    println("str : Empty? :" + isEmpty())
    length
}
var str2 : String? = "Hello!"
val len = str2?.run {
    println("str2 : Empty? :" + isEmpty()) // no it
    println("str2 Length = $length")
    length
} 
println(len) // 6

with

Access member of tis arugments

data class Data(val name: String, val index: Int)

val data1 = Data("Alice", 1)
with(data1) {
    println("$name:$index")
}

apply

Executes a block of code on an object and returns the object itself

In block, object reference is this, can skip

class Data2() {
    
    var name: String? = null
    
    var index: Int? = null
}

// Apply
var data2 = Data2()
val str = data2.apply {
   name = "Sun"
   index = 1
}.toString()
println(str)

also

Looks like apply. It executes a given block and return the object, inside of block object reference is it

class Data2() {
    
    var name: String? = null
    
    var index: Int? = null
}

var data3 = Data2().also {
    println(it.toString())
}
println(data3.name)
Android
スポンサーリンク
Professional Programmer2

コメント