gpt4 book ai didi

scala - 我的方法与 Predef 中的一致性之间存在隐含歧义的问题

转载 作者:行者123 更新时间:2023-12-02 07:48:17 25 4
gpt4 key购买 nike

以下代码,摘自Apocalisp的优秀系列博客: Type level programming in 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)

有人可以解释为什么会发生这种情况,是否可以解决?

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)

}
}

最佳答案

虽然我不能告诉你Predef.conforms的确切目的| ,我可以告诉你歧义错误似乎是正确的(不幸的是)。在来源的评论中,它甚至说 <:<由于Function1的歧义问题而被引入(说 Function2 但我想这是一个错误)。但是因为 <:<Function1 的子类它可以在任何时候传入 Function1是预期的,因此在您的情况下可以传入 <:<进行解析。

现在 implicit def conforms[A]: A <:< A效果(据我所知)每当一个方法需要一个类型 A => A , 隐式值为 A 就足够了在范围内。

在你的例子中是 implicit def hParseNil: HNil => HNilconforms 具有相同的优先级因此两者都可以同等应用。

我看到两种可能的解决方案:

  • 只需删除 hParseNil ,我认为您的代码仍然有效。
  • 隐藏Predefconforms通过命名你的相同:

    implicit def conforms: HNil => HNil = _ => new HNil

关于scala - 我的方法与 Predef 中的一致性之间存在隐含歧义的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5377492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com