2017-04-16 22 views
3

我用无形库模式匹配一​​个简单的无形HLIST

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) 

该代码会被罚款,如果我正在同一个正常的列表。

+2

您需要导入'shapeless。::',但没有'::'被视为'scala.immutable.collection。::'。 – Marth

+1

谢谢!那工作。 –

回答

3

您只需要导入,默认scala.Predefscala.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) 
    } 
}