I'm working with a Java API that passes around identifiers as strings. It seems a bit nicer to me to use typed symbols for this, so I wrote this:
object Helpers {
implicit def actionToString(action: Action): String =
action.getClass.getName.stripSuffix("$").replaceAll(".*\\$", "")
object Action{
def apply(name: String): Action = {
Class.forName("tutorial.HelloInput$Helpers$" + name).newInstance()
.asInstanceOf[Action]
}
}
sealed abstract class Action {
override def toString: String = actionToString(this)
}
final case class Rotate() extends Action
final case class Right() extends Action
final case class Left() extends Action
final case class Pause() extends Action
}
This allows "serialization" and "deserialization" of strings and Actions in a natural way, e.g., I can pattern match on Action(Pause)
, but I can also pass Pause()
to a Java library that expects a string thanks to the implicit conversion.
Is there a better way to do this, especially in terms of performance? Are there any problems with this method that may come back to bite me later?
I was reading a little about Phantom types in Dotty, and wonder if they might be used to improve performance for dealing with symbols (or maybe the new Enums would be the better alternative).