Vin Norman
Vin Norman

Reputation: 3302

Update object's property if not null, or create new object if null then set property

I'm trying to find the nicest, cleanest way to update a nullable object property that is also an object. Psuedo code:

class MyClass {
   val myNullableProperty: MyPropertyClass? 
}

Here's the ugly solution I have so far:

val myProperty = myClass.myNullableProperty ?: MyPropertyClass() // MyPropertyClass has default constructor values so this is fine instantiating like this in my example
myProperty.name = "Name" 
myClass.myNullableProperty = myProperty

This just feels not the best way of doing this. I feel there's some sort of solution using let/apply/with/run etc. - it feels wasteful to define the local variable myProperty like that, and then set it to myNullableProperty later.

I'm looking for something where I can either retrieve the existing property , or create the new property, and then immediately set the value on that property.

Upvotes: 0

Views: 1380

Answers (2)

Blue Jones
Blue Jones

Reputation: 385

If you wanna make it more kotlin-y:

myClass.myNullableProperty?.let {
   it.name = "Name"
} ?: run {
   myClass.myNullableProperty = MyPropertyClass().apply {
      name = "Name"
   }
}

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93639

Assign the value to itself, or a new instance if it's null:

myClass.myNullableProperty = myClass.myNullableProperty?: MyPropertyClass()

If you want to avoid further null checks:

myClass.myNullableProperty = (myClass.myNullableProperty?: MyPropertyClass()).apply{ 
    name = "Name" 
}

If access to the property is single-threaded, you could avoid all unnecessary assignments this way:

if (myClass.myNullableProperty == null)
    myClass.myNullableProperty = MyPropertyClass()
myClass.myNullableProperty!!.name = "Name"

Upvotes: 1

Related Questions