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

查看:93
本文介绍了“新" 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

如果要引用伴随对象的apply方法,请省略new:

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秘密地为您创建了一个伴侣对象,将其变成了这样:

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天全站免登陆