What is the meaning of “new {}” in Scala?

浪子不回头ぞ 提交于 2020-03-23 08:34:08

问题


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


回答1:


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 }



来源:https://stackoverflow.com/questions/46825794/what-is-the-meaning-of-new-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!