[英]How to define a nullable delegate member in Kotlin?
I need to decorate an instance in Java and would like the delegation to be in Kotlin (easier). 我需要用Java装饰一个实例,并希望委托使用Kotlin(更轻松)。
The problem is that I get a compilation error on the definition. 问题是我在定义中收到编译错误。
How can I define inner
to be able to receive null? 我如何定义
inner
才能接收null?
open class ConnectionDecorator(var inner: Connection?) : Connection by inner // Getting an error on the right inner
Example usage from Java: Java的用法示例:
new ConnectionDecorator(null).close();
* This is a simplified example, trying to use Kotlin's delegation in Java, where passed content can be null. *这是一个简化的示例,尝试在Java中使用Kotlin的委托,其中传递的内容可以为null。
You can provide a Null Connection Object if the inner
is null, for example: 如果
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
}
In fact, there is no need such a ConnectionDecorator
, it doesn't make sense, because when you using delegation you also need override some methods to provide additional operations, eg: log
. 实际上,不需要这样的
ConnectionDecorator
是没有意义的,因为使用委派时,您还需要重写某些方法来提供其他操作,例如: log
。 you can use wrap
method directly, for example: 您可以直接使用
wrap
方法,例如:
val connection:Connection? = null;
wrap(connection).close()
You should make the inner
to non-nullable and create ConnectionDecorator
instance by wrap
, for example: 您应该使
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()
Try This 尝试这个
ConnectionDecorator(null).close(); ConnectionDecorator(null).close();
open class ConnectionDecorator(var inner: Connection?) : Connection by inner!! 打开类ConnectionDecorator(var inner:Connection?):通过内部连接!
Hope its work 希望它的工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.