4

从数据容器(例如案例类)中提取类型的最佳方法是什么。

例如,如果我有一个type Tagged[U] = { type Tag = U}标记类型trait PID,它是标记的 Inttype ProductId = Int with Tagged[PID]或 scalaz 样式type ProductId = Int @@ PID,并说产品中的其他字段type Name = String @@ PName等,以及一个包含产品属性的数据容器;

case class Product(pid: ProductId, name: Name, weight: Weight)

我怎样才能编写一个通用的提取器A => B样式方法而不求助于反射?

原因是我想在运行时从 Product 容器中动态提取一个字段。即用户传入他们想要提取的产品的属性。

即,如果我想动态获取ProductId,我可以编写一个采用类型并返回值的方法,例如

trait Extractor[A] {
  def extract[B](i: A): B = //get type B from the Product class
}

还是我把事情复杂化了。

我可以编写简单的提取器类,它采用 A => B 函数并为每种类型定义它;

trait Getter[A, B] {
  def extract(i: A): B
}
//... mix this in...
trait GetPID extends Getter[Product, ProductId] {
  override def extract(implicit i: Product) = i.pid
}
trait GetName extends Getter[Product, Name] {
  override def extract(implicit i: Product) = i.name
}

然后在需要的地方添加它们。

val dyn = new DynamicProductExtractor with GetPID 
dyn.extract

但这似乎很麻烦。

我觉得 Lens 之类的东西在这里会很有用。

4

1 回答 1

8

为了一个完整的示例,假设我们有以下类型和一些示例数据:

import shapeless._, tag._

trait PID; trait PName; trait PWeight

type ProductId = Int @@ PID
type Name = String @@ PName
type Weight = Double @@ PWeight

case class Product(pid: ProductId, name: Name, weight: Weight)

val pid = tag[PID](13)
val name = tag[PName]("foo")
val weight = tag[PWeight](100.0)

val product = Product(pid, name, weight)

我在这里使用 Shapeless 的标签,但下面的所有内容都可以与 Scalaz 或您自己的Tagged. 现在假设我们希望能够在任意案例类中按类型查找成员,我们可以使用 Shapeless 创建一个提取器Generic

import ops.hlist.Selector

def extract[A] = new {
  def from[C, Repr <: HList](c: C)(implicit
    gen: Generic.Aux[C, Repr],
    sel: Selector[Repr, A]
  ) = sel(gen.to(c))
}

请注意,为了简单明了,我使用了结构类型,但您可以很容易地定义一个新的类来做同样的事情。

现在我们可以编写以下内容:

scala> extract[ProductId].from(product)
res0: Int with shapeless.tag.Tagged[PID] = 13

请注意,如果案例类有多个具有请求类型的成员,则将返回第一个。如果它没有任何具有正确类型的成员(例如类似的东西extract[Char] from(product)),你会得到一个很好的编译时错误。

您可以在这里使用镜头,但您需要或多或少地编写相同的机制——我不知道镜头实现可以为您提供按类型索引(例如,Shapeless 提供位置索引和按成员名称进行索引)。

(请注意,这并不是真正的“动态”,因为您在案例类中查找的类型必须在编译时静态已知,但在您上面给出的示例中也是如此。)

于 2015-02-15T18:09:32.313 回答