【发布时间】:2016-05-21 19:58:18
【问题描述】:
我有一个看起来像这样的案例类:
case class Color(name: String, red: Int, green: Int, blue: Int)
我正在使用 Shapeless 2.3.1 和 Scala 2.11.8。在寻找LabelledGeneric[Color] 的隐含值方面,我看到了与我的测试和 REPL 不同的行为。 (我实际上是在尝试自动派生一些其他类型类,但我也得到了null)
内部测试
package foo
import shapeless._
import org.specs2.mutable._
case class Color(name: String, red: Int, green: Int, blue: Int)
object CustomProtocol {
implicit val colorLabel: LabelledGeneric[Color] = LabelledGeneric[Color]
}
class GenericFormatsSpec extends Specification {
val color = Color("CadetBlue", 95, 158, 160)
"The case class example" should {
"behave as expected" in {
import CustomProtocol._
assert(colorLabel != null, "colorLabel is null")
1 mustEqual 1
}
}
}
此测试失败,因为 colorLabel 是 null。为什么?
REPL
从 REPL,我可以找到LabelledGeneric[Color]:
scala> case class Color(name: String, red: Int, green: Int, blue: Int)
defined class Color
scala> import shapeless._
import shapeless._
scala> LabelledGeneric[Color]
res0: shapeless.LabelledGeneric[Color]{type Repr = 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("red")],Int],shapeless.::[Int with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("green")],Int],shapeless.::[Int with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("blue")],Int],shapeless.HNil]]]]} = shapeless.LabelledGeneric$$anon$1@755f11d9
【问题讨论】: