加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 我的方法和Predef中的conforms之间隐含模糊的问题

发布时间:2020-12-16 09:24:16 所属栏目:安全 来源:网络整理
导读:以下代码取自Apocalisp的优秀博客系列: Type level programming in scala,并针对隐式解析方案进行了修改.但是,这不会编译,并显示以下消息: error: ambiguous implicit values:both method hParseNil in object HApplyOps of type = (com.mystuff.bigdata.c
以下代码取自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的歧义问题而引入(说功能2,但我猜这是一个错误).但是因为<:< Function1是Function1的一个子类,它可以在期望Function1的情况下传递,因此在你的情况下可以传入<:<为了hparse. 现在隐式def符合[A]:A<:< A具有(根据我的理解)每当方法期望类型A =>时的效果. A,在范围内具有A的隐式值就足够了.

在您的情况下隐式def hParseNil:HNil => HNil具有与conform相同的优先级,因此两者可以同等地应用.

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

>只需删除hParseNil,我认为您的代码仍然有效.
>通过命名你的相同来影响Predef的符合:

隐式def符合:HNil => HNil = _ =>新的HNil

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读