Scala:伴随对象和“新"对象关键词 [英] Scala: companion objects and "new" keyword

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

问题描述

在我最近关于在 Scala 中使用或省略new"关键字的帖子中(new"关键字在 Scala 中)有人告诉我,这个遗漏来自这样一个事实,即某些类具有用 apply 方法定义的伴生对象.我的问题是:我们是否能够分辨出或是否有任何通用规则来区分哪些类/对象具有伴随对象和应用方法?

In my recent posts about using or omitting a "new" keyword in Scala ( "new" keyword in Scala) I was told that the omission comes from the fact that certain classes have companion objects defined with apply method on them. My question is: are we able to tell or is there any general rule to distinguish which classes/objects have a companion object and apply method?

提前致谢,很抱歉这是一个愚蠢的问题,但来自 Java 背景,这有点令人困惑.

Thanks in advance and sorry of it's a stupid question, but coming from a Java background it is a bit confusing.

推荐答案

Scala API 文档,你在列表上看到一个小图标 左边.如果你点击它,你会转到所提到的类或特征的伴随对象的文档.

In the Scala API documentation, you see a little icon in the list on the left side. If you click on that, you go to the documentation of the companion object of the class or trait that's mentioned.

标准库中的大多数集合类和许多其他类都有带有 apply 方法的伴随对象.

Most of the collection classes and many other classes in the standard library have companion objects with apply methods.

对于 case 类,Scala 编译器会自动创建一个带有 apply 方法(以及其他方法)的伴随对象.

For case classes, the Scala compiler automatically creates a companion object with an apply method (as well as other methods).

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

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