How To Reference Nested Kotlin Scope Functions Using Labels
A Quick Tip For Optimizing Your Code Base
In this article, you will learn how to declare labels on Kotlin scope functions to distinguish between multiple Kotlin scopes of the same type.
Kotlin, as a programming language, is known for its broad toolset and easy-to-understand syntax. One notable feature that underlines this statement are Scope functions like apply
or let
.
Apply
specifically allows us to easily update an object without referencing the assigned variable over and over again.
Let’s say we have a class Parent
that, on the other hand, contains a variable of the class Child
. The child has a variable name
.
data class Parent(
var name: String,
var age: Int,
var child: Child
)
data class Child(
var name: String,
val age: Int
)
fun main() {
val parent = Parent(
name = "Hans",
age = 50,
child = Child(
name = "Friederich",
age = 10
)
)
}
So, when we now want to update the name
and the age
of the parent
variable instead of the following:
parent.name = "Fritz"
parent.age = 55