728x90
반응형
언제 무엇을 사용해야 할까요?
우선 with 는 다른 항목들과 사용법이 다릅니다.
인자를 받고 블록의 수행된 결과를 반환합니다. 재밋는 점은 마지막 줄의 결과값이 리턴되는데 어떠한 타입도 리턴이 가능합니다.
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#with).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
예시
fun withTest() {
println("with : ${with()}")
}
private fun with() = with("fun") {
val s: String = with("val") {
"<val start>$this<val end>"
}
"$s, <fun start>$this<fun end>"
}
결과 : with : <val start>val<val end>, <fun start>fun<fun end>
다음으로 나머지 항목들을 쉽게 확인 할 수 있는 예제 코드 및 결과입니다.
val test = 1
val alsoResult = test.also { origin ->
origin + 3
}
println("also result $alsoResult")
val letResult = test.let { origin ->
origin + 3
}
println("let result $letResult")
val applyResult = test.apply {
this + 3
}
println("apply result $applyResult")
val runResult = test.run {
this + 3
}
println("run result $runResult")
결과
also result 1
let result 4
apply result 1
run result 4
- 결과값의 차이 : let, run 는 블럭에 결과값을 넘기고 also, apply는 this 객체를 반환합니다.
- 블럭에 전달되는 값의 차이 : also, let 은 블록에 자신을 인자로 전달하며, apply, run 은 블록에 자신을 리시버 객체로 전달
반응형
'Development > Kotlin' 카테고리의 다른 글
[kotlin] for문 에서 collection withIndex 사용하기 (0) | 2021.04.02 |
---|---|
Kotlin cheat sheet (0) | 2021.01.05 |
코틀린 문서 벅역본 (0) | 2017.03.09 |
댓글