javakotlinnullablegetterbacking-field

Instantiate a variable in Kotlin only if it is a null?


Lets say, I have a variable:

var myObject : MyObject? = null

it should be cleared in some place :

myObject?.clear
myObject = null

and should be definitely non-nullable in a place of usage. In Java I can do something like this:

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

The question: How can I achieve that in Kotlin?

I found a suggestion to use elvis-operator:

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

but that does not assign a result (if new instance of MyObject would be created) to the myObject variable. Please help me with solution and explanation. thanks ahead


Solution

  • The issue is that the getter and setter of a property can't have different types. I'd suggest a separate nullable private property and a method for clearing 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 pattern more than once, write a delegate.