Pattern matching on a simple lifeless HLIST
I wrote this simple code using the shapeless library
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)
}
}
But it doesn't even compile
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)
This code would be fine if I was working with a regular list.
+3
source to share
1 answer
You just need import, by default scala.Predef
imports the statement ::
from 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)
}
}
There is one more option to import 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)
}
}
+5
source to share