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