Reputation: 451
Basically, I want to create an abstract class and several child classes. Each child class will have their own distinct enum set, but I want to be able to reference the enum from the parent class. Something like
abstract class Parent {
enum class TheEnum
}
class Class1: Parent() {
enum class TheEnum(val value: String) {
CASE_1("case 1"),
CASE_2("case 2"),
...
}
class Class1: Parent() {
enum class TheEnum(val value: String) {
JANUARY("january"),
FEBRUARY("february"),
...
}
Then I can have a function like someFunction(enum TheEnum)
, and pass either Class1
's enum or Class2
's enum as an argument to it. This is the crux of what I need to accomplish, because I am passing many of these similar classes into the same functions, and rather than rewrite every single function for each class, I can just have one function.
Is there something like Swift's TheEnum.self
?
Upvotes: 1
Views: 1230
Reputation: 380
Short answer is No. In kotlin enum's don't inherit from each other and their instances and the value of their members is defined at compile time like so
enum class TheEnum(val value: String) {
JANUARY("january"),
FEBRUARY("february")
}
At runtime you cannot pass something like TheEnum.JANUARY("december")
you can only pass TheEnum.JANUARY
Also since they can't inherit each other so it is just not possible to write a single function and pass different type of enums to them.
Is there something like Swift's TheEnum.self?
Also no. Enums in kotlin can be compared like
enum class A {
w, x
}
enum class B {
y, z
}
fun let(a: A) {
when(a) {
A.w -> ""
A.x -> ""
B.y -> "" //warning: Comparison of incompatible enums 'A' and 'B' is always unsuccessful
B.z -> "" //warning: Comparison of incompatible enums 'A' and 'B' is always unsuccessful
}
If you are in need of something more flexible you can take a look at sealed classes.
Upvotes: 2