kotlin 可以重新初始化的 by lazy

import kotlin.reflect.KProperty
class LazyIf(
private val initCondition: ((LazyIf, T?) -> Boolean)? = { _, v ->
v == null
},
private val initializer: () -> T,
) {
private var value: T? = null
var initCount = 0
private set

@Synchronized
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
    if (initCondition?.invoke(this, value) == true) {
        value = initializer()
        initCount++
    }
    val finalValue = value ?: run {
        val tmp = initializer()
        initCount++
        tmp
    }
    value = finalValue
    return finalValue
}

operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
    this.value = value
}

}

class LazyIfNullable(
private val initCondition: ((LazyIfNullable, (T?)) -> Boolean)? = { _, it -> it == null },
private val initializer: () -> T?,
) {
private var value: T? = null
var initCount = 0
private set

@Synchronized
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
    if (initCondition?.invoke(this, value) == true) {
        value = initializer()
        initCount++
    }
    return value
}

operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
    this.value = value
}

}

/**

  • @param initCondition: 初始化条件
  • @param initializer: 初始化函数
  • @return LazyIf
    */
    fun lazyIfNullable(
    initCondition: ((LazyIfNullable, (T?)) -> Boolean)? = { _, it -> it == null },
    initializer: () -> T?,
    ) = LazyIfNullable(initCondition, initializer)

/**

  • @param initCondition: 初始化条件
  • @param initializer: 初始化函数
  • @return LazyIf
    */
    fun lazyIf(
    initCondition: ((LazyIf, T?) -> Boolean)? = { _, v -> v == null },
    initializer: () -> T,
    ) = LazyIf(initCondition, initializer)
posted @ 2025-03-06 10:45  烟花易冷心易碎  阅读(26)  评论(0)    收藏  举报