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

Jukka Siivonen

04/01/2022, 10:19 AM
Another question about constructor usage in data classes, is something like this possible without cycle error?
Copy code
data class ReasonItem private constructor(
    val reason: Reason,
    val notes: String?
) {
    constructor(
        reason: FooReason
    ) : this(reason, null)

    constructor(
        reason: BarReason,
        notes: String
    ) : this(reason, notes)
}
of course I could create separate *Item types too but..
maybe two subtypes makes more sense because getter is still nullable in both cases
j

Joffrey

04/01/2022, 10:23 AM
Use
reason as Reason
when you want to call the private constructor from the others. That said, it might be more interesting to use a sealed class which does or does not have the
notes
property depending on the type
👍 1
Copy code
sealed class ReasonItem(open val reason: Reason)

data class FooReasonItem(
    override val reason: FooReason,
) : ReasonItem(reason)

data class BarReasonItem(
    override val reason: BarReason,
    val notes: String,
) : ReasonItem(reason)
j

Jukka Siivonen

04/01/2022, 10:25 AM
Yeah, also thanks for the "reason as Reason" tip
j

Joffrey

04/01/2022, 10:26 AM
Overloads are resolved statically at compile time based on the declared type of the variable, this is why the cast works
👍 1
2 Views