Search code examples
scalaobject-initialization

Scala : Calling methods of a class during object initialization


object Program {
   def main(args:Array[String])={
      val parent = new Parent{
         method()
      }
   }
}


class Parent{
   def method(){
       println("inside method")
   }
}

In the above code, I am instantiating a new instance of Parent class. Now I thought this is similar to C# object initialization syntax. But I am able to call some methods here as well. What is this use case of this feature? Does this have any name?


Solution

  • Actually, you are instantiating an instance of an anonymous class that extends Parent, and calling a base class method from within the constructor. I don't think there is any special name for it.