reactormonk
07/04/2022, 9:26 AMenum class
with an "other value"? Aka
enum class Status(val value: Int) {
Present(2),
Absent(1),
Error(value)
}
?Joffrey
07/04/2022, 9:27 AMError
to support different values depending on the case?reactormonk
07/04/2022, 9:29 AMJoffrey
07/04/2022, 9:31 AMStatus.Error
with different values. So I would say you have 2 main options:
1. if you don't really need the error code (the value
property), you may keep an enum but remove the value
property - just map your error codes to one of the 3 enum states without storing the error code in the enum value. Note that, in Kotlin, enums don't need to be associated with a number or anything - maybe that's the missing piece of the puzzle for you
2. if you do need the code, it means you want different instances of those enum values (with different codes). In that case, you cannot use an enum but you can use a sealed class
insteadenum class Status {
Present,
Absent,
Error;
companion object {
fun fromStatusCode(code: Int) = when(code) {
1 -> Absent
2 -> Present
else -> Error
}
}
}
I'm assuming 1 and 2 here are probably not what you want (assuming you had assigned numbers to the enum entries just because you thought you had to). But you could map your actual status codes here.reactormonk
07/04/2022, 9:38 AMsealed class CardStatus(val value: Int) {}
class CardPresent() : CardStatus(2)
class CardAbsent(): CardStatus(1)
class CardError(value: Int): CardStatus(value)
fun Int.toCardStatus(): CardStatus {
return when(this) {
(2) -> CardPresent()
(1) -> CardAbsent()
else -> CardError(this)
}
}
Joffrey
07/04/2022, 9:42 AMcompanion object would be the more conventional way to go about it?Not necessarily, but it depends on where you put this extension on
Int
. Because Int
is a very common type, there is a chance this will pollute auto-completion in your project, hence why I would personally tend to favor CardStatus.fromCode(Int)
over extensions on Int
, if this is a public function like in your case. if it's a private function, it's quite okCardPresent
and CardAbsent
always hold the same value, they can be `object`s instead of classes (you don't need new instances every time)
2. If the naming makes sense with nesting, you can nest your sealed class's subclasses inside the sealed class, so they are referred to with the SealedParent.Child
syntax. In your case, this would read `CardStatus.Present`/`CardStatus.Absent`/`CardStatus.Error` - but that's a matter of tastereactormonk
07/04/2022, 9:48 AMtoString
in terms of clarity, but then you should add enough context šJoffrey
07/04/2022, 9:50 AMtoString()
, it may be worth making CardError
a data class
then šreactormonk
07/04/2022, 9:53 AM