我经常发现,在对每个实现执行相同操作之前,我需要提取密封特质的类型:
举个例子。
sealed trait Trait
case class Foo() extends Trait
case class Bar() extends Trait
// ... lots of other implementations
// *must* take a `Trait`, not a `T <: Trait`
def thing(t: Trait): ??? = t match {
case f: Foo => // something with the instance and specific type
case b: Bar => // something with the instance and specific type
// ... same thing again for other implementations
}
举个例子。
// typically provided by somebody else...
trait Thing[T] { def thingy: String }
implicit def thing[T]: Thing[T] = new Thing[T] { def thingy = "stuff" }
def thing(t: Trait): String = t match {
case Foo() => implicitly[Thing[Foo]].thingy
case Bar() => implicitly[Thing[Bar]].thingy
// ...
}
我希望能减少在这方面所涉及的样板代码。
def thing[A <: Trait: Thing](a: A)
似乎已经足够了。 - Michael Zajacdef thing(t: Thing)
而不是def thing[T <: Thing](t: T)
。 - fommilT
都有一个Thing
实例吗?这并不会改变问题的定义,因为我仍然需要处理大量的模式匹配,并在每个右侧使用相同的代码。 - fommil