![](/img/trans.png)
[英]In Kotlin, is it possible to call a member extension function specifying both the object dispatched to and the receiver? If so, how?
[英]Is it possible in Kotlin to have a member function with a nullable receiver?
我可以使用可为空的接收器而不是成员函数来实现扩展函数。 这有效:
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")
}
但这不会:
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")
}
我的解决方案:我的目标是让方法检测问题并处理它,而不是让调用者这样做。 我最终做的是将函数放在伴随对象中,这为我提供了我想要的封装并允许我处理问题。
您可以编写这样的扩展函数,嵌套在类中,但嵌套将扩展函数的范围限制在类内,类似于将其设置为protected
。 这可能有用,在类的其他实例上调用它:
class Test {
fun Test?.foo() = println("foo ext $this")
fun bar(other: Test?) {
other.foo()
}
}
如果你想在可为空的实例上调用它,你应该简单地在类之外定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.