“新"Scala 中的关键字 [英] "new" keyword in Scala

查看:22
本文介绍了“新"Scala 中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题 - 在 Scala 中创建对象时,我们应该什么时候应用 new 关键字?是在我们只尝试实例化 Java 对象时吗?

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?

推荐答案

当您想引用 class 自己的构造函数时,请使用 new 关键字:

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

class Foo { }

val f = new Foo

省略 new 如果您指的是伴随对象的 apply 方法:

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

如果您制作了案例类:

case class Foo()

Scala 偷偷为你创建了一个伴生对象,把它变成这样:

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

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

所以你可以这样做

f = Foo()

最后,请记住,没有规则说配套apply方法必须是构造函数的代理:

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

而且,既然你提到了 Java 类:是的——Java 类很少有带有 apply 方法的伴随对象,所以你必须使用 new 和实际的类的构造函数.

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.

这篇关于“新"Scala 中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆