3

我正在尝试创建模仿无形类型类的自定义类型类。它看起来像这样:

  trait View[Record] {
    type Result <: HList
    def apply(r: Record): Result
  }

  object View extends LowPriorityLiftFunction1{
    type Aux[Record, L <: HList] = View[Record] {type Result = L}
    implicit def atView[Record: View] = at[Record](implicitly[View[Record]].apply)
  }

假设我提供它的功能是这样的:

object toHView extends ->( (_:Int) + 1)

implicit def provideView[Record, L <: HList]
(implicit generic: Generic.Aux[Record, L],
 mapper: Mapper[toHView.type, L])
: View.Aux[Record, mapper.Out] =
  new View[Record] {
    type Result = mapper.Out

    def apply(r: Record) = mapper(generic.to(r))
  }

所以如果我们定义:

case class Viewable(x: Int, y: Int, z : Int)
case class NotViewable(x: Int, y: Long, z : Int)

然后

val view = View(Viewable(1, 2, 3)) // is 2 :: 3 :: 4 :: HNil

val noView = View(NotViewable(1, 2, 3)) // is HNil

如果我尝试获取这里的麻烦

view.head

我有

错误:找不到参数的隐式值 c: IsHCons[View[Viewable]#Result]

我如何定义这个类型类以便以后有效地使用它的所有类型成员?

当然我可以摆脱类型成员:

trait View[Record, Result <: HList] {
  def apply(r: Record): Result
}

object View extends LowPriorityLiftFunction1{
  implicit def atView[Record, Result]
  (implicit view: View[Record, Result]) = at[Record](view.apply)
}

object toHView extends ->((_: Int) + 1)
implicit def provideView[Record, L <: HList]
(implicit generic: Generic.Aux[Record, L],
 mapper: Mapper[toHView.type, L])
: View[Record, mapper.Out] =
  new View[Record, mapper.Out] {
    type Result = mapper.Out  

    def apply(r: Record) = mapper(generic.to(r))
  }

但从此时起

val view = View(Viewable(1, 2, 3))

我遇到了“模棱两可的隐含价值”问题

4

1 回答 1

5

好的,这里是:更改

implicit def atView[Record: View] = at[Record](implicitly[View[Record]].apply)

implicit def atView[Record](implicit v: View[Record]) = at[Record](v.apply(_))

原因是implicitly在处理精炼类型成员时会失去精度,因此HList编译器会Int :: Int :: Int :: HNil吐出一个相当无用的View#Result.

使用隐式参数而不是上下文绑定似乎可以保留精炼类型。

此外,shapeless'是保留类型改进the的替代方法,尽管在这种情况下它似乎不起作用implicitly

这是一个implicitly丢失精度的例子,取自theshapeless 的实现

scala> trait Foo { type T ; val t: T }
defined trait Foo

scala> implicit val intFoo: Foo { type T = Int } = new Foo { type T = Int ; val t = 23 }
intFoo: Foo{type T = Int} = \$anon\$1@6067b682

scala> implicitly[Foo].t  // implicitly loses precision
res0: Foo#T = 23

scala> implicitly[Foo].t+13
<console>:13: error: type mismatch;
  found   : Int(13)
  required: String
              implicitly[Foo].t+13
                                 ^

scala> the[Foo].t         // the retains it
res1: Int = 23

scala> the[Foo].t+13
res2: Int = 36
于 2015-07-31T14:29:45.813 回答