Kotlin has delegated properties which is a very nice feature. But sometimes get()
and set()
methods are not enough. Let's say I want to create a Closeable
object lazily and to close it later. Here's an example of how such delegate property could be implemented:
fun <T : Closeable> closeableLazy(initializer: () -> T) =
CloseableLazyVal(initializer)
class CloseableLazyVal<T : Closeable>(
private val initializer: () -> T
) : ReadOnlyProperty<Any?, T> {
private var value: T? = null
override fun get(thisRef: Any?, desc: PropertyMetadata): T {
if (value == null) {
value = initializer()
}
return value
}
fun close() {
value?.close()
}
}
这就是我想使用它的方式:
private val stream by closeableLazy { FileOutputStream("/path/to/file") }
fun writeBytes(bytes: ByteArray) {
stream.write(bytes)
}
override fun close() {
stream::delegate.close() // This line will not compile
}
不幸的是,这种方法不起作用,因为Kotlin似乎不允许直接访问属性委托.有什么办法可以满足我的要求吗?或者有没有计划在Kotlin中添加这样的功能,因为这将是一个非常简洁的特性.