TIL

아이템 21 일반적인 프로퍼티 패턴은 프로퍼티 위임으로 만들어라

// stdlib가 제공하는 지연 초기화
val value by lazy { createValue() }

// stdlib가 제공하는 관찰자 패턴
var items: List<Item> by 
	Delegates.observablie(listOf()) { _, _, _ -> notifyDataSetChanged() }
// 프로퍼티가 사용될 때마다 로깅을 하는 위임 프로퍼티 구현 예
var token: String? by LoggingProperty(null)

private class LoggingProperty<T>(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): T {
		val name = prop.name
		print("$name changed from $value to $newValue")
		value = newValue
	}
@JvmField
private val `token$delegate` = 
	LoggingProperty<String?>(null)
	
val token String? 
	get() = `token$delegate`.getValue(this, ::token)
	set(value) {
		`token$delegate`.setValue(this, ::token, value)
	}
inline operator fun <V, V1: V>Map<in String, V> // stdlib에 정의된 확장 함수
	.getValue(thisRef: Any?, property: KProperty<*>): V1 = 
		getOrImplicitDefault(property.name) as V1
		
val map: Map<String, Any> = mapOf (
	"name" to "Marcin",
)

val name by map
print(name) // Marcin