scala case class equals (==) not working as expected
-
09-01-2021 - |
Question
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??
Solution
Case classes (or objects) inheriting from case classes is a bad practice, and is illegal as of Scala 2.9.1. Use object
instead of case object
to define Red
, Green
and Blue
.
OTHER TIPS
Why should that be true? Green is a companion object, c is an instance. They aren't equal.
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.
object Black extends Color(0x00000000)
val black1 = Color(0x00000000)
black1 == Black
res1: Boolean = true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow