with
한 객체안에서 연속된 동작을 취해야 할 때 유용하게 사용가능하다.
//T.() -> 자기자신에 it 키워드 없이 접근가능.
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
with(person) {
name = "ari"
}
println(person) // Person(name=ari, age=18)
//expression
val ari = with(person) {
name = "ari" //setter는 기본적으로 Unit
//name
}
println(ari) //Kotlin.Unit
//println(ari) -> "ari"
recyclerView.with {
// recyclerView.layoutManager
layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL)
// recyclerView.adapter
adapter = this@ Activity.adapter
// recyclerView.addItemDecoration()
addItemDecoration(Adapter.ContentDecoration(context))
}
T를 with의 인자로 전달한다
block 안에서는 마치 object 내부처럼 property를 자유롭게 접근한다
표현식으로 사용한다면 반환 값 R은 괄호 제일 마지막 라인의 값이 된다
특정 instance의 내부 값들을 수정하거나 조합할 때 사용하면 좋다
Last updated