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

scala – 如何正确键入注释此HList?

发布时间:2020-12-16 09:25:15 所属栏目:安全 来源:网络整理
导读:sealed abstract trait HListcase class :+:[H,T : HList](head: H,tail: T) extends HList { def :+:[T](v: T) = new :+:(v,this)}case object HNil extends HList { def :+:[T](v: T) = new :+:(v,this)}object HListExpt { def main(args: Array[String])
sealed abstract trait HList

case class :+:[H,T <: HList](head: H,tail: T) extends HList {
  def :+:[T](v: T) = new :+:(v,this)
}

case object HNil extends HList {
  def :+:[T](v: T) = new :+:(v,this)
}

object HListExpt {
  def main(args: Array[String]) {
    val me: String :+: Int :+: Symbol :+: HNil.type = "Rahul" :+: 20 :+: 'Male :+: HNil
    println(me.head,me.tail.head)
  }
}

在尝试编译上面的代码时,我得到以下编译器错误:

error: type mismatch;
found   : :+:[java.lang.String,:+:[Int,:+:[Symbol,object HNil]]]
required: :+:[String,HNil.type]]]
val me: String :+: Int :+: Symbol :+: HNil.type = "Rahul" :+: 20 :+: 'Male :+: HNil

我在这做错了什么?键入注释上述HList的正确方法是什么?

PS:当我删除类型注释时,代码编译得很好.

解决方法

这里的根本问题是从不推断单例类型.这是一个演示:

scala> case object A      
defined module A

scala> A                  
res6: A.type = A

scala> identity[A.type](A)
res7: A.type = A

scala> identity(A)        
res8: object A = A

为什么是这样? Quoth Odersky et.人.在Scala编程中,§27.6:

Usually [singleton] types are too
specific to be useful,which is why
the compiler is reluctant to insert
them automatically.

所以,让我们明确提供类型参数:

sealed abstract trait HList

case class :+:[H,this)
}

case object HNil extends HList {
  def :+:[T](v: T) = new :+:[T,HNil.type](v,this)
}

val me: String :+: Int :+: Symbol :+: HNil.type = "Rahul" :+: 20 :+: 'Male :+: HNil
println(me.head,me.tail.head)

额外链接:

> Singleton Types are Mean and Spiteful

(编辑:李大同)

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

    推荐文章
      热点阅读