如果为空,您可以提供空连接对象inner
,例如:
// 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
to不可为空并通过创建ConnectionDecorator
实例wrap
,例如:
// 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()