Reputation: 1577
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.
Upvotes: 0
Views: 420
Reputation: 93581
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
. 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.
Upvotes: 1