【问题标题】:How to correctly type-annotate this HList?如何正确键入注释此 HList?
【发布时间】:2011-04-23 21:23:36
【问题描述】:
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,:+:[Int,:+:[Symbol,HNil.type]]]
val me: String :+: Int :+: Symbol :+: HNil.type = "Rahul" :+: 20 :+: 'Male :+: HNil

我在这里做错了什么?对上述HList 进行类型注释的正确方法是什么?

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

【问题讨论】:

    标签: scala scala-2.8 hlist


    【解决方案1】:

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

    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 等。人。在 Scala 编程中,第 27.6 节:

    通常 [singleton] 类型也是 具体有用,这就是为什么 编译器不愿意插入 自动。

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

    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 :+:[T, HNil.type](v, this)
    }
    
    val me: String :+: Int :+: Symbol :+: HNil.type = "Rahul" :+: 20 :+: 'Male :+: HNil
    println(me.head, me.tail.head)
    

    奖励链接:

    【讨论】:

      【解决方案2】:

      我不知道为什么,但是如果 HNil 被定义为一个类,那么一切都会编译:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-17
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        • 2021-01-22
        相关资源
        最近更新 更多