https://kotlinlang.org logo
Title
t

tipsy

03/31/2019, 11:52 AM
is it possible to create different callbacks based on an enum type?
on(Event.TYPE_ONE) { int ->
    // an int is available here
}

on(Event.TYPE_TWO) { string ->
    // a string is available here
}
s

Shawn

03/31/2019, 12:44 PM
my first thought is that this might be possible with sealed classes
this works:
sealed class Event {
  object TYPE_ONE : Event()
  object TYPE_TWO : Event()
}

fun on(enum: Event.TYPE_ONE, block: (Int) -> Any) {

}

fun on(enum: Event.TYPE_TWO, block: (String) -> Any) {

}

on(Event.TYPE_ONE) {
  it.inc()
}

on(Event.TYPE_TWO) {
  it.length
}
but if the enum needs to be an enum, then I don’t think you can do what you’re asking for here
t

tipsy

03/31/2019, 12:58 PM
thanks @Shawn, i guess it doesn't need to be an enum
sealed classes seem like the way to go
s

Shawn

03/31/2019, 12:58 PM
Might I ask what the larger goal is here? Are you just working on a fancy DSL or something?
It just seems unusual to use enums/sealed classes like this, at least from my experience anyhow
t

tipsy

03/31/2019, 1:00 PM
not so fancy, just an event system
events should include relevant information
l

louiscad

03/31/2019, 5:31 PM
BTW, there's an intention in the IDE to convert an enum class to a sealed class and back to an enum class