Home > OS >  Scala: singleton object vs anonymous class
Scala: singleton object vs anonymous class

Time:06-24

In Scala, an inner singleton object and an anonymous inner class seem to achieve the same end. What are the differences between them, and when should I prefer using one over the other?

Inner singleton object:

object Main extends App {
  object A {
    val a = 7
  }
  
  println(A.a)
}

Anonymous inner class:

object Main extends App {
  val A = new {
    val a = 7
  }
  
  println(A.a)
}

CodePudding user response:

There is one visible difference between them and I shall explain:

An object behaves like a lazy val. In fact, it can be seen as a shorthand for the definition of a lazy val with an anonymous class which describes the object's contents.

This description is taken directly from Programming in Scala 4th Ed. (Chapter 20. Abstract Members. Subchapter 20.5 Initializing abstract vals) by M. Odersky, B. Venners and L. Spoon.

Here is an example, that shows the difference:

object Program extends App {
  object Demo {
    val a = {
      println("initializing a from Demo")
      7
    }
  }

  val A = new {
    val a = {
      println("initializing a from A")
      8
    }
  }

  println(Demo.a)
  println(A.a)
}

Output:

initializing a from A
initializing a from Demo
7
8

As you can see, when you instantiate an anonymous class. Val a is evaluated before the reference A is initialized. That is not the same with Demo. Val a is only initialized where the object Demo is first used, and that is the line that prints it, not where it is defined.

You should use objects when you want to code in a more functional and/or be more efficient in terms of memory. Because objects are lazy evaluated, they get evaluated exactly when they are needed, if they are needed. If they aren't needed, they will not be evaluated. So you avoid a memory overhead right there, for example if the evaluation of the anonymous class is an compute-intensive operation, this can make a difference if you use a lot of them in an enterprise application.

  • Related