How should I use `sealed class` or `hashmap` or `enums` in a specific case?

143 Views Asked by At

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.

  1. In the current situation, I may only use as to manually modify the type, which is not elegant.
  2. If I replace enum with hashmap, it should be able to solve the problem that the IDE cannot smart cast. But when using the use statement, it loses the characteristics of enum or sealed class.
  3. If I use sealed class instead of enum, the sealed class cannot be traversed, that is, you cannot use it like this enum.values().

What is the best solution in this case?

0

There are 0 best solutions below