The relationship between an 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])

he prints:

isAssignableFrom: true
equality: true
instanceOf:false

How is this possible? Don't see this in Java yet.

+4
source share
1 answer

In each example, you do not mean the same concept TestMatch.

  • classOf[TestMatch]and instanceOf[TestMatch]are referred to TestMatchas type. Singletones do not define type.
  • TestMatch.something() - method call for singleton object TestMatch

Now, which can be a little confusing, the following:

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

I assume Scala gives priority to the class when singleton is an object companion.

Edit:

, scala.Singleton SDK Scala, ... :

object MySingleton
println(MySingleton.isInstanceOf[MySingleton])

, singleton . .

println(MySingleton.isInstanceOf[MySingleton.type]) // true

, , .

class MyClassWithCompanion
object MyClassWithCompanion

val x = new MyClassWithCompanion

println(MyClassWithCompanion.isInstanceOf[MyClassWithCompanion])      // false
println(MyClassWithCompanion.isInstanceOf[MyClassWithCompanion.type]) // true
println(MyClassWithCompanion.isInstanceOf[x.type]                     // false

, :

  • .type - ,
  • x.type , x -, MyClass.type , -. MyClassWithCompanion.type - ( ),
  • . x singleton x, , .
+3

Source: https://habr.com/ru/post/1651212/


All Articles