Hanbit the Developer
Kotlin Documentation | Scope functions 본문
Category: Standard library
문서 링크: https://kotlinlang.org/docs/scope-functions.html
Function selection
각 함수의 의도:
- Executing a lambda on non-null objects: let
val name: String? = "John"
name?.let { println("Hello, $it") } // Executes the lambda only if name is non-null
- Introducing an expression as a variable in local scope: let
val result = someObject.let { calculateResult(it) } // Introduces the result of the expression as a variable in local scope
- Object configuration: apply
val person = Person().apply {
name = "John"
age = 30
address = "123 Main St"
}
- Object configuration and computing the result: run
val result = someObject.run {
performCalculation()
computeResult()
}
- Running statements where an expression is required: non-extension run
val result = run {
val a = 5
val b = 10
a + b // Expression required
}
- Additional effects: also
val name = "John"
val length = name.length.also { println("Length of name: $it") } // Performs additional effect of printing the length
- Grouping function calls on an object: with
val person = Person()
with(person) {
setName("John")
setAge(30)
setAddress("123 Main St")
}
takeIf and takeUnless
predicate가 각각 true, false이면 값을 반환하고, 아닐 경우 null을 반환한다.
val number = Random.nextInt(100)
println("number: $number")
val evenOrNull = number.takeIf { it % 2 == 0 }
val oddOrNull = number.takeUnless { it % 2 == 0 }
println("even: $evenOrNull, odd: $oddOrNull")
number: 3
even: null, odd: 3
number: 2
even: 2, odd: null
scope functions와 결합할 때 유용하다:
input.indexOf(sub).takeIf { it >= 0 }?.let {
println("The substring $sub is found in $input.")
println("Its start position is $it.")
}
'Kotlin' 카테고리의 다른 글
Kotlin Documentation | Coroutines basics (0) | 2023.05.24 |
---|---|
Kotlin Documentation | Opt-in requirements (0) | 2023.05.24 |
Kotlin Documentation | Map-specific operations (0) | 2023.05.24 |
Kotlin Documentation | Set-specific operations (0) | 2023.05.24 |
Kotlin Documentation | List-specific operations (0) | 2023.05.24 |