Search code examples
scalaanonymous-types

What is the meaning of "new {}" in Scala?


I am studying about .sbt extension file reference docs. What codes I am confused is:

lazy val version = new {
    val finatra = "2.1.2"
}

I know val finatra can be accessed by version.finatra, but it seems like "object singleton." Such like this:

object version {
    val finatra = "2.1.2"
}

In this case, I can also access val finatra by version.finatra.
I know the later one is the way to create "object singleton". How about the former one? Thanks


Solution

  • In short, it is creating new instance of Anonymous Type

    According to the Scala Language Spec:


    Consider the following structural instance creation expression:

    new { def getName() = "aaron" }
    

    This is a shorthand for the general instance creation expression

    new AnyRef{ def getName() = "aaron" }
    

    The latter is in turn a shorthand for the block

    { class anon$X extends AnyRef{ def getName() = "aaron" }; new anon$X }