简单的无形HLIST上的模式匹配

时间:2017-04-16 18:04:50

标签: scala shapeless

我使用无形图库

编写了这个简单的代码
import shapeless.LabelledGeneric
case class Icecream(name: String, numberOfCherries: Int, inCone: Boolean)

object ShapelessRecordEx2 extends App {
   val gen = LabelledGeneric[Icecream]
   val hlist = gen.to(Icecream("vanilla", 2, false))
   hlist match {
      case h :: _ => println(h)
   }
}

但是甚至没有编译

Error:(12, 14) constructor cannot be instantiated to expected type;
 found   : scala.collection.immutable.::[B]
 required: shapeless.::[String with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("name")],String],shapeless.::[Int with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("numberOfCherries")],Int],shapeless.::[Boolean with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("inCone")],Boolean],shapeless.HNil]]]
      case h :: _ => println(h)

如果我使用普通列表,这段代码就没问题了。

1 个答案:

答案 0 :(得分:6)

您只需要导入,默认情况下scala.Predef会从::导入scala.collection.immutable.List运算符。

import shapeless.LabelledGeneric
import shapeless.::
case class Icecream(name: String, numberOfCherries: Int, inCone: Boolean)

object ShapelessRecordEx2 extends App {
   val gen = LabelledGeneric[Icecream]
   val hlist = gen.to(Icecream("vanilla", 2, false))
   hlist match {
      case h :: _ => println(h)
   }
}

还有另一个选项,即导入ListCompat._

import shapeless.HList.ListCompat._

object ShapelessRecordEx2 extends App {
  val gen = LabelledGeneric[Icecream]
  val hlist = gen.to(Icecream("vanilla", 2, false))
  hlist match {
    case h #: _ => println(h)
  }
}