如何在Scala中实现异构容器

Yan*_*san 2 collections scala heterogeneous shapeless

我需要一个异构的,类型安全的容器来存储不相关的类型A,B,C.

这是一种类型级规范:

trait Container {
  putA(a: A) 
  putB(b: B)
  putC(c: C)
  put(o: Any) = { o match {
    case a: A => putA(a)
    case b: B => putB(b)
    case c: C => putC(c)
  }
  getAllAs : Seq[A]
  getAllBs : Seq[B]
  getAllCs : Seq[C]
}
Run Code Online (Sandbox Code Playgroud)

哪种类型是支持此容器的最佳套件?

是否值得为类型A,B,C创建容器[T]类型类?

THKS.

Gab*_*lla 7

正如其他人所说,你可以利用无形' Coproduct类型.这是一个例子.

// let's define a Coproduct of the two types you want to support
type IS = Int :+: String :+: CNil

// now let's have a few instances
val i = Coproduct[IS](42)
val i2 = Coproduct[IS](43)
val s = Coproduct[IS]("foo")
val s2 = Coproduct[IS]("bar")

// let's put them in a container
val cont = List(i, s, i2, s2)

// now, do you want all the ints?
val ints = cont.map(_.select[Int]).flatten

// or all the strings?
val strings = cont.map(_.select[String]).flatten

// and of course you can add elements (it's a List)
val cont2 = Coproduct[IS](12) :: cont
val cont3 = Coproduct[IS]("baz") :: cont2
Run Code Online (Sandbox Code Playgroud)

现在,这当然不是通用容器最直观的API,但可以使用Coproductfor表示多种类型,轻松地将逻辑封装在自定义类中.

这是一个实现的草图

import shapeless._; import ops.coproduct._

class Container[T <: Coproduct] private (underlying: List[T]) {
  def ::[A](a: A)(implicit ev: Inject[T, A]) =
    new Container(Coproduct[T](a) :: underlying)

  def get[A](implicit ev: Selector[T, A]) =
    underlying.map(_.select[A]).flatten

  override def toString = underlying.toString
}

object Container {
  def empty[T <: Coproduct] = new Container(List[T]())
}
Run Code Online (Sandbox Code Playgroud)

scala> type IS = Int :+: String :+: CNil
defined type alias IS

scala> val cont = 42 :: "foo" :: "bar" :: 43 :: Container.empty[IS]
cont: Container[IS] = List(42, foo, bar, 43)

scala> cont.get[Int]
res0: List[Int] = List(42, 43)

scala> cont.get[String]
res1: List[String] = List(foo, bar)
Run Code Online (Sandbox Code Playgroud)