stella stella - 3 months ago 4
Scala Question

Relationship between instance of classes and its companion object

I have the following class and companion object:

class TestMatch(val i: Int)

object TestMatch{
def apply(i: Int) = new TestMatch(i)
def unapply(tm : TestMatch): Option[Int] = Some(tm.i)
}


Now consider the following simple program:

println("isAssignableFrom: " + classOf[TestMatch].isAssignableFrom((tm.getClass)))
println("equality: " + classOf[TestMatch].equals((tm.getClass)))
println("instanceOf:" + TestMatch.isInstanceOf[TestMatch])


it prints:

isAssignableFrom: true
equality: true
instanceOf:false


How is it possible? Have not come across with this in Java yet.

Answer

You are not referring to the same TestMatch concept in each example.

  • classOf[TestMatch] and instanceOf[TestMatch] refer to TestMatch as a type.
  • TestMatch.something() is a call to a method on the singleton object TestMatch

Now what can be a bit confusing is the following:

object Singleton
println(Singleton.isInstanceOf[Singleton]) // prints true

I'm guessing Scala gives the priority to the class when a singleton is a companion-object.