如何在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 Connection对象 ,例如:

 // 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(空).close();

打开类ConnectionDecorator(var inner:Connection?):通过内部连接!

希望它的工作