Kotlin的惰性委托(delegate)属性lazy和lazyFast有什么区别?因为它看起来像相同的代码。
private val key: String by lazy {
if (arguments != null && arguments?.getString(Constants.KEY) != null) {
return@lazy arguments?.getString(Constants.KEY).toString()
} else {
return@lazy ""
}
}
private val key: String by lazyFast {
if (arguments != null && arguments?.getString(Constants.KEY) != null) {
return@lazyFast arguments?.getString(Constants.KEY).toString()
} else {
return@lazyFast ""
}
}
最佳答案
懒惰:-
lazy返回一个Lazy对象,该对象处理lambda函数(初始化程序),该函数根据线程执行模式(LazyThreadSafetyMode)以稍微不同的方式执行初始化。
public actual fun <T> lazy(mode: LazyThreadSafetyMode, initializer: ()
-> T): Lazy<T> =
when (mode) {
LazyThreadSafetyMode.SYNCHRONIZED -> SynchronizedLazyImpl(initializer)
LazyThreadSafetyMode.PUBLICATION -> SafePublicationLazyImpl(initializer)
LazyThreadSafetyMode.NONE -> UnsafeLazyImpl(initializer)
}
lazyFast:-
lazyFast还返回模式为LazyThreadSafetyMode.NONE的Lazy对象。
fun <T> lazyFast(operation: () -> T): Lazy<T> = lazy(LazyThreadSafetyMode.NONE) {
operation()
}
LazyThreadSafetyMode.SYNCHRONIZED:-
LazyThreadSafetyMode.PUBLICATION:-
并发访问未初始化的Lazy实例值时,可以多次调用
LazyThreadSafetyMode.NONE:-