如何正确地对这个 HList 进行类型注释? [英] How to correctly type-annotate this HList?

查看:58
本文介绍了如何正确地对这个 HList 进行类型注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)
  }
}

在尝试编译上述代码时,我收到以下编译器错误:

On trying to compile the above code, I get the following compiler error:

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 进行类型注释的正确方法是什么?

What am I doing wrong here? What would be the correct way to type-annotate the above HList?

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

PS: The code compiles fine when I remove the type annotation.

推荐答案

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

The root problem here is that singleton types are never inferred. Here's a demonstration:

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 节:

Why is this? Quoth Odersky et. al. in Programming in Scala, §27.6:

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

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

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

So, let's explicitly provide the type argument:

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)

奖励链接:

这篇关于如何正确地对这个 HList 进行类型注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆