如何为密封特征删除重复的案例陈述

丰米尔

我经常发现,在对每个实现执行相同操作之前,需要提取密封特征的类型:

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
  // ...
}

我想减少这样做的样板。

丰米尔

更新:如今,我们将通过无形使用typeclass派生。例如https://github.com/fommil/shapeless-for-mortals

事实证明,您可以使用无形的多态函数和联合乘积来执行此操作:

  object thing extends Poly1 {
    implicit def action[T <: Trait: Thing] = at[T](
      a => implicitly[Thing[T]].thingy
    )
    // magic that makes it work at the sealed trait level
    def apply(t: Trait): String =
      Generic[Trait].to(t).map(thing).unify
  }

然后可以像

println(thing(Foo(): Trait))

我想使它更容易通过抽象类来编写(action现在暂时不要将隐式参数传递给),例如

abstract class MatchSealed[In, Out] extends Poly1 {
  implicit def poly[T <: In] = at[T](action)

  def action[T <: In](t: T): Out

  import ops.coproduct.Mapper
  def apply[R <: HList](in: In)(
    implicit
      g: Generic.Aux[In, R],
      m: Mapper[this.type, R]
  ): Out = {
    val self: this.type = this
    g.to(in).map(self).unify
  }
}

但这失败了Mapper[self.type, g.Repr],最后一行丢失了。我不知道缺少哪个隐式函数,但是我怀疑它是self.type。我真的很想捕捉,realisedSelf.type但是我不知道该怎么做。

UPDATE:事实是无法获得,Mapper因为它需要访问已实现的object Unable to HList

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章