stella stella - 10 months ago 44
Scala Question

Is companion always instance of the class?

I read the article about singleton objects in scala but didn't find abything about if it's an instance of the class.
The following simple program tells that for this particular case it's true:

class TestMatch(val i: Int)

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

I tried to test it as this:

println(TestMatch.isInstanceOf[TestMatch]) //false

but it generated the warning
fruitless type test
I'm not sure how to perform such test.


objects are always an instance of an anonymous class whose body is the object definition's body. If the definition does not include an extends clause, that class inherits directly from AnyRef.

So the only way the TestMatch object could be an instance of the TestMatch class would be if you wrote object TestMatch extends TestMatch(something) {...}. Since you didn't do that, the TestMatch is not an instance of TestMatch in your code.

PS: The reason you're getting that warning for your test code is that Scala already knows at compile time exactly what the type of TestMatch is, so it knows that the run-time test can only ever result in false and is thus "fruitless". Generally you'd use run-time type tests when the exact type of something is not determined until run time and the test may thus may be true or false.