본문 바로가기
프로그래밍 놀이터/Kotlin, Coroutine

[Effective Kotlin] Item 21 : Use property delegation to extract common property patterns

by 돼지왕 왕돼지 2022. 3. 18.
반응형

이 글은 Effective Java 를 완독하고, Kotlin 을 상용으로 사용하는 개발자 입장에서
Effective Kotlin 글 중 새로운 내용, remind 할 필요 있는 부분, 핵심 내용 등만 추려 정리한 내용입니다.

 

#
lazy 와 Delegates.observable 이 유용하다.

val value by lazy { createValue() }

var key: String? by Delegates.observable(null) { _, old, new ->
	Log.e("key changed from $old to $new")
}

var items: List by Delegates.observable(listOf()) { _, _, _ ->
	notifyDataSetChanged()
}

 

#

View binding, Resource Binding, DI, Data Binding 등에도 사용될 수 있다.

 

#

var token: String? = null
	get() {
		print("token returned value $field")
		return field
	}
	set(value) {
		print("token changed from $field to $value")
		field = value
	}

var token2: String? by LoggingProperty(null)

private class LoggingProperty(var value: T) {
	operator fun getValue(thisRef:Any?, prop:KProperty<*>): T{
		print("${prop.name} returned value $value")
		return value
	}
    
	operator fun setValue(thisRef:Any?, prop:KProperty<*>, newValue:T){
		print("${prop.name} changed from $value to $newValue")
		value = newValue
	}
}

 

#
context 에 따라 다르게 동작하는 녀석도 만들 수 있다.

class SwipeRefreshBinderDelegate(val id: Int){
	private var cache: SwipeRefreshLayout? = null
    
	operator fun getValue(activity: Activity, prop:KProperty<*>):SwipeRefreshLayout{
		return cache ?: activity.findViewById<SwipeRefreshLayout>(id).also { cache = it }
	}

	operator fun getValue(fragment: Fragment, prop:KProperty<*>):SwipeRefreshLayout{
		return cache ?: fragment.view.findViewById<SwipeRefreshLayout>(id).also { cache = it }
	}
}

 

 

Summary

 

 

 

반응형

댓글