LastExceed
08/23/2019, 12:11 PMif (x != null) {
y = x
}
is there a shorter way to do this? I recall there being some way by using the ?
operator but im not sure if that was in kotlin or another languageMarko Mitic
08/23/2019, 12:12 PMif (x!=null) y=x
😄LastExceed
08/23/2019, 12:12 PMMarko Mitic
08/23/2019, 12:12 PMy= x?:y
Marc Knaup
08/23/2019, 12:13 PMx?.let { y = it }
LastExceed
08/23/2019, 12:13 PMShawn
08/23/2019, 12:14 PMLastExceed
08/23/2019, 12:14 PMShawn
08/23/2019, 12:14 PMMarc Knaup
08/23/2019, 12:15 PMMarko Mitic
08/23/2019, 12:16 PMShawn
08/23/2019, 12:16 PMMarko Mitic
08/23/2019, 12:17 PMval z = x ?: y
might be better optionMarc Knaup
08/23/2019, 12:18 PMif
won't even work (reliably) in cases where a smart cast is not possible.LastExceed
08/23/2019, 12:21 PMoldCharacterData.Update(newCharacterData)
fun CharacterData.Update(newData: CharacterData) {
if (newData.position != null) {
this.position = newData.position
}
//the same code for all 47 fields
}
Marc Knaup
08/23/2019, 12:23 PMLastExceed
08/23/2019, 12:24 PMMarc Knaup
08/23/2019, 12:24 PM.copy
and the approach of Marko, on line per property.LastExceed
08/23/2019, 12:25 PMMarc Knaup
08/23/2019, 12:26 PMdata.copy(
position = newData.position ?: data.position,
...
)
LastExceed
08/23/2019, 12:27 PM.copy
do here?Marc Knaup
08/23/2019, 12:27 PMLastExceed
08/23/2019, 12:38 PMMarc Knaup
08/23/2019, 12:38 PMLastExceed
08/23/2019, 1:19 PMkarelpeeters
08/23/2019, 1:20 PMSinan Kozak
08/23/2019, 1:21 PMLastExceed
08/23/2019, 1:21 PM.copy
optimized enough to not bother about that?Marc Knaup
08/23/2019, 1:32 PMLastExceed
08/23/2019, 1:34 PMMarc Knaup
08/23/2019, 1:39 PMLastExceed
08/23/2019, 1:51 PMWhy do you update a data class instance rather than creating a new one containing the data merged from the precious one and the update?
Then you could useisnt this in the end be the same as just creating a new object manually since i have to pass a value for every property to .copy (either the new value or the old if the new is null) ?and the approach of Marko, on line per property.copy
.copy
is precisely not having to pass the old value again, but wouldnt marko's approach be doing just that?Marc Knaup
08/23/2019, 1:52 PM.copy()
is most helpful if you only need to change some of the properties.
I don’t know how your relevant code works so I don’t know what case makes more sense for you 🙂data class Data(val a: A? = null, val b: B? = null)
received = Data()
…
for each message:
when message
is A -> received = received.copy(a=message)
is B -> received = received.copy(b=message)