scala 案例类等于 (==) 未按预期工作
我一定在这里错过了一些愚蠢的东西。我有这个:
case class Color(val rgb:Int) {
private val c = rgb - 0xff000000
val r = (c & 0xff0000) >> 16
val g = (c & 0x00ff00) >> 8
val b = (c & 0x0000ff)
}
case object Red extends Color(0xffff0000)
case object Green extends Color(0xff00ff00)
case object Blue extends Color(0xff0000ff)
然后我希望打印 true:
val c = Color(0xff00ff00)
println(c == Green)
为什么不呢?
I must be missing something silly here. I have this:
case class Color(val rgb:Int) {
private val c = rgb - 0xff000000
val r = (c & 0xff0000) >> 16
val g = (c & 0x00ff00) >> 8
val b = (c & 0x0000ff)
}
case object Red extends Color(0xffff0000)
case object Green extends Color(0xff00ff00)
case object Blue extends Color(0xff0000ff)
Then I expect this to print true:
val c = Color(0xff00ff00)
println(c == Green)
Why doesn't it??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 Case 类继承 Case 类(或对象)是一种不好的做法,并且从 Scala 2.9.1 开始是非法的。使用
object
而不是case object
来定义Red
、Green
和Blue
。Case classes (or objects) inheriting from case classes is a bad practice, and is illegal as of Scala 2.9.1. Use
object
instead ofcase object
to defineRed
,Green
andBlue
.为什么应该这是真的? Green 是伴生对象,c 是实例。它们不相等。
Why should that be true? Green is a companion object, c is an instance. They aren't equal.
我认为这是一个相关的问题:“为什么它扩展的案例对象和案例类不相等”。
使用 Scala 2.12.2,
我在示例中添加了以下几行,现在对象等于类实例。
res1:布尔值= true
I think it was a relevant question: "Why case object and case class it extends are not equal".
Using Scala 2.12.2
I added following lines to your example and and now object is equal to the class instance.
res1: Boolean = true