gpt4 book ai didi

scala - 简单的 Shapeless HLIST 上的模式匹配

转载 作者:行者123 更新时间:2023-12-04 23:15:22 25 4
gpt4 key购买 nike

我使用 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)

如果我使用的是普通列表,这段代码就可以了。

最佳答案

您只需要导入,默认情况下 scala.Predef进口 ::运算符(operator)来自 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)
}
}

关于scala - 简单的 Shapeless HLIST 上的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43440367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com