以下代码取自Apocalisp的优秀博客系列: scala中的类型级编程,并针对隐式解析方案进行了修改.但是,这不会编译,并显示以下消息:
error: ambiguous implicit values:
both method hParseNil in object HApplyOps of type => (com.mystuff.bigdata.commons.collections.hlist.HNil) => com.mystuff.bigdata.commons.collections.hlist.HNil
and method conforms in object Predef of type [A]<:<[A,A]
match expected type (com.mystuff.bigdata.commons.collections.hlist.HNil) => com.amadesa.bigdata.commons.collections.hlist.HNil
val l = hparse[HNil,HNil](HNil)
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么会发生这种情况,以及它是否可以修复?
sealed trait HList
final case class HCons[H, T <: HList](head: H, tail: T) extends HList {
def :+:[T](v: T) = HCons(v, this)
}
sealed class HNil extends HList {
def :+:[T](v: T) = HCons(v, this)
}
object HNil extends HNil
// aliases for building HList types and for pattern matching
object HList {
type :+:[H, T <: HList] = HCons[H, T]
val :+: = HCons
}
object HApplyOps
{
import HList.:+:
implicit def hParseNil: HNil => HNil = _ => HNil
implicit def hParseCons[InH,OutH,TIn <:HList,TOut<:HList](implicit parse:InH=>OutH,parseTail:TIn=>TOut): (InH :+: TIn) => (OutH :+: TOut) =
in => HCons(parse(in.head),parseTail(in.tail))
def hparse[In <: HList, Out <: HList](in:In)(implicit parse: In => Out):Out = in
}
object PG {
import HList._
def main(args: Array[String]) {
import HApplyOps._
val l = hparse[HNil,HNil](HNil)
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我无法告诉你确切的目的Predef.conforms,但我可以告诉你歧义错误似乎是正确的(不幸的是).在消息来源的评论中,它甚至说<:<是因为模糊性问题而引入的Function1(说Function2但我认为这是一个错误).但是因为它<:<是一个子类,Function1它可以在Function1预期的时候传入,所以在你的情况下它可以传入<:<hparse.
现在,implicit def conforms[A]: A <:< A有效(根据我的理解),每当方法需要一个类型时A => A,A在范围内有一个隐含值就足够了.
在您的情况下,implicit def hParseNil: HNil => HNil具有相同的优先级conforms,因此两者可以同等地应用.
我看到两种可能的解决方案
hParseNil,我认为你的代码仍然有效.影着Predef的conforms被命名你一样的:
implicit def conforms: HNil => HNil = _ => new HNil
| 归档时间: |
|
| 查看次数: |
867 次 |
| 最近记录: |