Scala case class equals (==) not working as expected

I must be missing something stupid here. I have it:

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 is this not so?

+7
source share
3 answers

Class classes (or objects) inheriting case classes are bad practice and are illegal like Scala 2.9.1. Use object instead of case object to define Red , Green and Blue .

+13
source

Why should this be true? Green is a companion object, c is an instance. They are not equal.

0
source

I think this was an important question: "Why is the case object and the case class that it extends not equal."

Using Scala 2.12.2

I added the following lines to your example, and now the object is equal to the class instance.

 object Black extends Color(0x00000000) val black1 = Color(0x00000000) black1 == Black 

res1: Boolean = true

0
source

All Articles