I use sealed classes to distinguish normal functions from suspend functions.
sealed class Function {
class SuspendFunction(val execute: suspend () -> Boolean) : Function() {
suspend operator fun invoke() {
execute()
}
}
class NormalFunction(val execute: () -> Boolean) : Function() {
operator fun invoke() {
execute()
}
}
}
Then I need some data to display in the display layer, I use enum.values()
.
enum class Work(val function: Function) {
A(Function.SuspendFunction { true }),
B(Function.NormalFunction { true })
}
Then I need to do various follow-up operations against Work.function
.
fun run(work: Work) {
when (work) {
Work.A -> {
work.function()
}
Work.B -> {
}
}
}
But this throws an error:
Expression 'function' of type 'Function' cannot be invoked as a function. The function 'invoke()' is not found
I think IDE no smart cast Function
to NormalFunction
.
This puts me in an embarrassing situation, I don't know how to choose to use enum
or sealed class
or hashmap
.
- In the current situation, I may only use
as
to manually modify the type, which is not elegant. - If I replace
enum
withhashmap
, it should be able to solve the problem that the IDE cannot smart cast. But when using theuse
statement, it loses the characteristics ofenum
orsealed class
. - If I use
sealed class
instead ofenum
, the sealed class cannot be traversed, that is, you cannot use it like thisenum.values()
.
What is the best solution in this case?