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.
r
Are you saying
fun B?.toA() = this?.toA() ?: A(42)
doesn't look very nice? If so, I'm not sure I understand what you're asking.
d
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.
r
Ah, I think I must have misread that part. The way I see it, that wouldn't make much sense, as, if the class def is available, that's basically what not-null means, though I can see how that's a rather circular argument.