[英]How to define a nullable delegate member in Kotlin?
我需要用Java装饰一个实例,并希望委托使用Kotlin(更轻松)。
问题是我在定义中收到编译错误。
我如何定义inner
才能接收null?
open class ConnectionDecorator(var inner: Connection?) : Connection by inner // Getting an error on the right inner
Java的用法示例:
new ConnectionDecorator(null).close();
*这是一个简化的示例,尝试在Java中使用Kotlin的委托,其中传递的内容可以为null。
如果inner
为null,则可以提供Null连接对象 ,例如:
// v--- the `var` is unnecessary
open class ConnectionDecorator(var inner: Connection?) : Connection by wrap(inner)
fun wrap(connection: Connection?): Connection = when (connection) {
null -> TODO("create a Null Object")
else -> connection
}
实际上,不需要这样的ConnectionDecorator
是没有意义的,因为使用委派时,您还需要重写某些方法来提供其他操作,例如: log
。 您可以直接使用wrap
方法,例如:
val connection:Connection? = null;
wrap(connection).close()
您应该使inner
成为非空值,并通过wrap
创建ConnectionDecorator
实例,例如:
// v--- make it to non-nullable
open class ConnectionDecorator(var inner: Connection) : Connection by inner {
fun close(){
inner.close();
log.debug("connection is closed");
}
}
val source:Connection? = null;
// v--- wrap the source
val target:Connection = ConnectionDecorator(wrap(source))
target.close()
尝试这个
ConnectionDecorator(null).close();
打开类ConnectionDecorator(var inner:Connection?):通过内部连接!
希望它的工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.