Sam
06/01/2023, 10:59 AM@JvmInline
value class Status(private val code: Int) {
private constructor(status: KnownStatus) : this(status.code)
val name: String? get() = KnownStatus.values().find { it.code == code }?.name
companion object {
val Good = Status(KnownStatus.Good)
val Bad = Status(KnownStatus.Bad)
val Ugly = Status(KnownStatus.Ugly)
}
private enum class KnownStatus(val code: Int) {
Good(1), Bad(2), Ugly(3)
}
}
Adam S
06/01/2023, 11:25 AMSam
06/01/2023, 12:27 PMTobias Suchalla
06/01/2023, 12:35 PMdata class Status(
val code: Int,
val name: String? = null
) {
companion object {
val Good = Status(1, "Good")
val Bad = Status(2, "Bad")
val Ugly = Status(3, "Ugly")
}
}
Or if you want exhaustive when
over the known values:
sealed class Status(open val code: Int, val name: String?) {
object Good : Status(1, "Good")
object Bad : Status(2, "Bad")
object Ugly : Status(2, "Ugly")
data class Arbitrary(override val code: Int) : Status(code, null)
}
Sam
06/01/2023, 12:41 PMStatus(1) == Status.Good
to always be true. I’d like to avoid a situation where I can have Status(1, "foo") != Status.Good
🤔equals
function. I’m never a fan of those, though 😬Tobias Suchalla
06/01/2023, 1:15 PM(Status.Arbitrary(1) as Status) == (Status.Good as Status)
But it works perfectly with data classes:
https://pl.kotl.in/7shbgVZN8Matteo Mirk
07/04/2023, 10:13 AMStatus(1, "foo") == Status.Good
work
ref: https://kotlinlang.org/docs/data-classes.html#properties-declared-in-the-class-body