0

I created a class ApplyDemo with private construtor as

class ApplyDemo private{
    override def toString()="ApplyDemo"
}

I created companion object of the class as

object ApplyDemo
{
     def apply()={
            Console.println("calling Apply");
            new ApplyDemo
        }
}

Now I created a main app class as :

object MainApp extends App{

        val a=ApplyDemo;
        Console.println(a);
}

for curiosity pupose I put a println statement in apply method . but this is not called. I am just curious to know why println is not called.

P.S. both class and companion are in same file

Thanks

optional
  • 3,260
  • 5
  • 26
  • 47

1 Answers1

0

I was able to get the answer in scala repl: Expression :

val a= ApplyDemo

is assigning a type of ApplyDemo to variable a and scala repl says :

a: ApplyDemo.type = ApplyDemo$@xxxxxx

and expression

val a= ApplyDemo()

calls apply method in companion class and repl says.

calling Apply
a1: ApplyDemo = ApplyDemo

Thanks to bjfletcher

optional
  • 3,260
  • 5
  • 26
  • 47