Java – variables are instantiated in kotlin only when kotlin is empty?

It can be said that I have a variable:

var myObject:MyObject? = null

It should be cleared somewhere:

myObject?.clear
myObject = null

And the place of use should never be empty In Java, I can do this:

private MyObject getMyObject(){
  if(myObject == null) {
    myObject = new MyObject()
  }
  return myObject
}

Question: how can this be achieved in kotlin?

I found suggestions for using Elvis operator:

private fun getMyObject() = myObject ?: MyObject()

However, this does not assign the result (if you want to create a new instance of MyObject) to the MyObject variable Please help me solve and explain thank you

Solution

The problem is that property getters and setters cannot have different types I suggest a separate nullable private property and a method to clear it:

private var _myObject: MyObject? = null

var myObject: MyObject // or val,depending
    get() {
        if (_myObject == null) { _myObject = MyObject() }
        return _myObject!!
    }
    set(value: MyObject) { 
        _myObject?.clear()
        _myObject = value
    }

fun clearMyObject() {
    _myObject?.clear()
    _myObject = null
}

If you need this mode more than once, write delegate

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>