Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

new operator - "new" keyword in Scala

I have a very simple question - when should we apply the new keyword when creating objects in Scala? Is it when we try to instantiate Java objects only?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the new keyword when you want to refer to a class's own constructor:

class Foo { }

val f = new Foo

Omit new if you are referring to the companion object's apply method:

class Foo { }
object Foo {
    def apply() = new Foo
}

// Both of these are legal
val f = Foo()
val f2 = new Foo

If you've made a case class:

case class Foo()

Scala secretly creates a companion object for you, turning it into this:

class Foo { }
object Foo {
    def apply() = new Foo
}

So you can do

f = Foo()

Lastly, keep in mind that there's no rule that says that the companion apply method has to be a proxy for the constructor:

class Foo { }
object Foo {
    def apply() = 7
}

// These do different things
> println(new Foo)
test@5c79cc94
> println(Foo())
7

And, since you mentioned Java classes: yes -- Java classes rarely have companion objects with an apply method, so you must use new and the actual class's constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...