let
- data의 null 체크를 할 때 주로 사용
val name : String? = ""
name?.let {
println("name $it length ${it.length}")
}
-> 예제
fun test() {
val name : String? = ""
name?.let {
println("name $it length ${it.length}")
} ?: let {
println("null")
}
}
Calls the specified function [block] with this value as its argument and returns its result.
public inline fun <T, R> T.let(block : (T) -> R) : R = block(this)
apply
- 생성과 동시에 값을 초기화할 때 유용
val textView = TextView(this)
textView.text = "button"
textView.setTextColor(getColor(R.color.abc_background_cache_hint_selector_material_dark))
textView.setOnClickListener { }
-> apply 적용
val textView = TextView(this).apply {
text = "button"
setTextColor(getColor(R.color.abc_background_cache_hint_selector_material_dark))
setOnClickListener { }
}
Calls the specified function [block] with this value as its receiver and returns this value.
public inline fun <T> T.apply(block : T.() -> Unit) : T { block() : return this }
run
- 이미 생성한 객체에 대하여 재 접근시 주로 사용
textView.text = "click button"
textView.setOnClickListener { }
-> 연속적인 접근을 줄여준다.
textView.run {
text = "click button"
setOnClickListener { }
}
Calls the specified function [block] with this value as its receiver and returns its result.
public inline fun <T, R> T.run(block : T.() -> R) : R = block()
with
- View에 접근할 때 주로 사용
fun onBindView() {
with(itemView) {
// ... itemView에 접근하기
}
}
Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
public inline fun <T, R> with(receiver : T, block : T.() -> R) : R = receiver.block()
also
- add v1.1
Calls the specified function [block] with this value as its argument and returns this value.
public inline fun <T> T.also(block (T) -> Unit) : T { block(this) : return this }
data class Block(var name : String = "", var age : Int = 10)
fun Block.copyName(age : Int) = Block().also {
it.name = this.name
it.age = age
}
@Test
fun test() {
val block = Block("ABC")
val temp = block.copyName(20)
println("block $block temp $temp")
}
block Block(name=ABC, age=10) temp Block(name=ABC, age=20)
takeIf
- add v1.1
Returns this value if it satisfies the given [predicate] or null, if it doesn't
public inline fun <T> T.takeIf(predicate : (T) -> Boolean) : T? = if (predicate(this)) this else null
fun test() {
val block = Block("ABC")
println("out ${block.takeIf { it.age > 10 }}")
}
takeUnless
- add v1.1
Returns this value if it does not satisfies the given [predicate] or null, if it does
public inline fun <T> T.takeUnless(predicate : (T) -> Boolean) : T? = if (!predicate(this)) this else null
fun test() {
val block = Block("ABC")
println("out ${block.takeUnless { it.age > 10 }}")
}
data class Block(var name : String = "", var age : Int = 10)
'# 02 > 코틀린' 카테고리의 다른 글
[Kotlin] SAM Class (0) | 2019.07.15 |
---|---|
[Kotlin] Generics (0) | 2019.07.15 |
[Kotlin] Higher-Order Functions (0) | 2019.07.12 |
[Kotlin] Class etc (0) | 2019.07.12 |
[Kotlin] Sealed Classes (0) | 2019.07.12 |