在Scala中动态选择类型类

时间:2019-06-10 20:29:04

标签: scala typeclass

我想将案例类序列化和反序列化为JSON,并在将其反序列化之后,根据其子类型,我想以不同的方式处理它们。像这样:

  sealed trait Salutation
  case class Hello(name: String)
  case class Greetings(name: String)
  case class HeyThere(name: String)

  trait Handler[A] {
    def greet(salutation: A)
  }

  implicit val helloSalutation: Handler[Hello] =
    new Handler[Hello] {
      def greet(salutation: Hello) = println(s"Hello, ${salutation.name}")
    }
  implicit val greetingsSalutation: Handler[Greetings] =
    new Handler[Greetings] {
      def greet(salutation: Greetings) = println("Greetings.")
    }
  implicit val heyThereSalutation: Handler[HeyThere] =
    new Handler[HeyThere] {
      def greet(salutation: HeyThere) = println("Hey there!")
    }

  val action = deserializeSalutationFromJson[Salutation](jsonStringFromSomewhere) 
  // NOTE: _action_ will be of the correct subtype, e.g. Greeting

  /* TODO val handler = select which handler to use based the type of action */

  handler.greet(action)

Scala中基于JSON动态类型进行选择的一种好的模式是什么?

0 个答案:

没有答案