by란?
특정 처리를 다른 객체에게 넘기는 것을 의미한다.
코틀린에서 by의 사용은 주로 두가지로 나누어 진다.
첫번째는 프로퍼티 접근자(Property Accessors)의 구현을 다른 객체에 위임(Delegate)하는 것이다.
주로 안드로이드 개발을 하면서 흔히 사용되는 by lazy, by inject(), by mutableStateOf()등 있다.
private val viewModel: SomeViewModel by lazy {
ViewModelProvider(requireActivity())[SomeViewModel::class.java]
}
private val viewModel: SomeViewModel by viewModels()
var someState by remember { mutableStateOf(false) }
위에서 사용되는 by를 이해하기 위해 간단한 예시를 하나 살펴보자
변수를 선언하고 변수의 getter와 setter가 호출될 때 이에 대한 정보를 print하고 싶은 경우가 있다고 가정해 보자
이 경우 아래와 같이 by를 이용하면 변수가 새로 선언될 때마다 변수들을 print할 수 있게 된다.
class ExampleUnitTest {
@Test
fun main() {
var intValue by PrintValueInfo(10)
intValue = 123
println(intValue)
}
}
class PrintValueInfo<T>(private var value: T) {
operator fun getValue(
thisRef: Any?,
property: KProperty<*>): T {
println("Get property name : ${property.name} thisRef : $thisRef value : $value")
return value
}
operator fun setValue(
thisRef: Any?,
property: KProperty<*>,
value: T) {
println("Set property name : ${property.name} thisRef : $thisRef originValue :${this.value} newValue : $value")
this.value = value
}
}
출력)
Set property name : intValue thisRef : null originValue :10 newValue : 123
Get property name : intValue thisRef : null value : 123
123
그러므로 위에 나열된 by lazy, by inject(), by mutableStateOf()등도 by에 의해 선언되면 지정되었던 작업이 이루어(provide by, delegate) 지기 때문에 by를 사용하는 것 이다.
두번째로는 인터페이스의 구현을 다른 개체에 위임하는 것이다.
class ExampleUnitTest {
interface Base {
val message: String
fun print()
}
class BaseImpl(val x: Int) : Base {
override val message = "BaseImpl: x = $x"
override fun print() { println(message) }
}
class Derived(b: Base) : Base by b { //b를 위임함으로 b가 구현한 BaseImpl의 멤버와 함수를 사용하는게 가능하다.
override val message = "Message of Derived"
}
@Test
fun main() {
val b = BaseImpl(10)
val derived = Derived(b)
derived.print()
println(derived.message)
}
}
출력)
BaseImpl: x = 10
Message of Derived
위와 같이 Derived class에 구현되어 있지 않은 print()함수를 Base 인터페이스를 구현한 BaseImpl로 부터 위임을 받아 사용이 가능하게 된다.
참고자료
https://kotlinlang.org/docs/reference/keyword-reference.html#soft-keywords
https://medium.com/mobile-app-development-publication/kotlin-by-made-simple-c6c08c1c16c4
'Kotlin' 카테고리의 다른 글
[Kotlin] 코틀린에서의 Null 처리 방법 (4) | 2024.11.05 |
---|---|
[Kotlin] 컬렉션(Collection) 함수 (9) | 2024.11.04 |
[Kotlin] open class와 abstract class (0) | 2024.11.02 |
[Kotlin] 깊은 복사 (Deep Copy) 3가지 방법 (0) | 2024.11.02 |
[Kotlin] Object 키워드 (with companion object) (0) | 2024.11.02 |