For example, if I have the following data class:
data class Data(
val name: String = "",
val number: Long = 0
)
And functions that can return null
:
fun newName(): String? {}
fun newNumber(): Long? {}
I know I can use the following to use the value of the functions if they are not null
:
val newName = newName()
val newNumber = newNumber()
val data = Data(
if (newName != null) newName else "",
if (newNumber != null) newNumber else 0
)
But is there a way to just use the default value specified in the constructor of the Data
class when the values are null
?
I could not find anything in the documentation, but I was hoping something like this would work:
val data = Data(newName()?, newNumber()?)
But that does not compile.
if (newName != null) newName else ""
you can just usenewName ?: ""
. It's called elvis operator. – Squawk