20 Ağustos 2021 Cuma

Kotlin run function

Giriş
Açıklaması şöyle
Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.

Scope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.
There are a few scope functions
- let
- with
- run
- apply
- also
run metodu
run() metodunun iki tane hali var. Açıklaması şöyle
run has two variants, one is an extension function to Template class and another one is not an extension function to Template class.
Extension Function
Örnek
Şöyle yaparız
class Employee {
    var firstName: String? = null
    var age: Int = 0
}

val employee: Employee? = Employee()
employee?.firstName = "Suneet"
employee?.age = 27

employee?.run {
    println(age)
}
Not Extension Function
Örnek
Şöyle yaparız
val alphaNumeric = run {
val digits = "0-9" val aplhabets = "A-Za-z" Regex("[$digits$aplhabets]+") } for (match in alphaNumeric.findAll("+1234 -FFFF I-am?-a!string?!")) { println(match.value) } //this will print 1234 FFFF I am a string


Hiç yorum yok:

Yorum Gönder