Another question about constructor usage in data c...
# getting-started
j
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
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
Yeah, also thanks for the "reason as Reason" tip
j
Overloads are resolved statically at compile time based on the declared type of the variable, this is why the cast works
👍 1