https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

David Kubecka

02/22/2023, 2:56 PM
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

Thiago

02/22/2023, 2:59 PM
Copy code
fun B?.toA(): A = A(this?.param ?: DefaultValue)
d

David Kubecka

02/22/2023, 3:04 PM
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

Ruckus

02/22/2023, 5:16 PM
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

David Kubecka

02/22/2023, 5:49 PM
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

Ruckus

02/22/2023, 6:47 PM
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.
4 Views