[英]Is it possible in Kotlin to have a member function with a nullable receiver?
I can implement an extension function with a nullable receiver but not a member function.我可以使用可为空的接收器而不是成员函数来实现扩展函数。 This works:
这有效:
class TestMe (var xyz:String) {
}
fun TestMe?.textX(xxx:String) {
if (this != null)
xyz = xxx
else println("this is null")
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
val x : TestMe? = null
x.textX("whatever")
println("hello world")
}
But this doesn't:但这不会:
class TestMe (var xyz:String) {
fun TestMe?.textX(xxx:String) {
if (this != null)
xyz = xxx
else println("this is null")
}
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
val x : TestMe? = null
x.textX("whatever")
println("hello world")
}
The solution for me : My goal here was to have the method detect the problem and deal with it rather than have the caller do that.我的解决方案:我的目标是让方法检测问题并处理它,而不是让调用者这样做。 What I ended up doing was to put the function in the companion object which gives me the encapsulation I wanted and also allows me to deal with problems.
我最终做的是将函数放在伴随对象中,这为我提供了我想要的封装并允许我处理问题。
You can write extension functions like this, nested inside a class, but nesting limits the extension function's scope to within the class, similar to making it protected
.您可以编写这样的扩展函数,嵌套在类中,但嵌套将扩展函数的范围限制在类内,类似于将其设置为
protected
。 This potentially could have a use, calling it on other instances of the class:这可能有用,在类的其他实例上调用它:
class Test {
fun Test?.foo() = println("foo ext $this")
fun bar(other: Test?) {
other.foo()
}
}
If you want to call it on nullable instances, you should simply define it outside the class.如果你想在可为空的实例上调用它,你应该简单地在类之外定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.