How to best make a conversion method with a defaul...
# getting-started
d
How to best make a conversion method with a default for the null receiver? Currently, I have this:
Copy code
data class A(param: Int)
data class B(param: Int) {
  fun toA() = A(param)
}
I want to make the converter work also on a nullable receiver providing some default value. I know I can do the following:
Copy code
data class B(param: Int)

fun B?.toA() = this?.let { A(param) } ?: A(42)
but wonder whether there's a better option. At least if I can somehow keep the non-nullable
toA
inside the class definition (keeping its name) and refer to it in
fun B?.toA()
. UPDATE: I realize now I can indeed refer to original
toA
from
B?.toA()
. Still it doesn't look very nice...
t
Copy code
fun B?.toA(): A = A(this?.param ?: DefaultValue)
d
Hmm, that seems to be better only in the single param case IMO 😞 Moreover, I'm maybe more interested in the option of keeping the converter inside the class def.
Yeah, that's not so horrible. As I said
I'm maybe more interested in the option of keeping the converter inside the class def.