kotlin:扩展方法和null接收者
在obj.method()
扩展方法中, obj.method()
是SomeUtil.method(obj)
的语法糖。 它允许obj
为null。
Kotlin扩展方法是静态解析的,所以我认为它是和我写的时候一样的语法糖
fun Any.stringOrNull() = this?.toString()
我收到了关于非空接收方不必要的安全呼叫的警告。 这是否意味着我不能像lombok那样在空对象上调用扩展函数?
如果将其定义为可以为空的types的扩展名,则可以在可空对象上调用它:
fun Any?.stringOrNull() = ...
否则,就像使用其他方法一样,您必须使用安全呼叫操作员 。
除了给出的答案,请参阅文档 :
可空接收者
请注意,可以使用可为空的接收方types来定义扩展。 这样的扩展可以在一个对象variables上调用,即使它的值为
null
,也可以在body中检查this == null
。 这允许你在Kotlin中调用toString()
而不检查null
:检查发生在扩展函数内部。fun Any?.toString(): String { if (this == null) return "null" // after the null check, 'this' is autocast to a non-null type, so the toString() below // resolves to the member function of the Any class return toString() }