简体   繁体   English

Scala:伴侣对象和“新”关键字

[英]Scala: companion objects and “new” keyword

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. 在我最近关于在Scala中使用或省略“new”关键字(Scala中的“new”关键字 )的帖子中,我被告知遗漏来自于某些类具有使用apply方法定义的伴随对象的事实。 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? 我的问题是:我们能够告诉或者是否有任何一般规则来区分哪些类/对象具有伴随对象和应用方法?

Thanks in advance and sorry of it's a stupid question, but coming from a Java background it is a bit confusing. 在此先感谢并抱歉这是一个愚蠢的问题,但是从Java背景来看,它有点令人困惑。

In the Scala API documentation , you see a little icon Scala API文档中 ,您会看到一个小图标 在此输入图像描述 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. 如果单击它,则转到上面提到的类或特征的伴随对象的文档。

Most of the collection classes and many other classes in the standard library have companion objects with apply methods. 标准库中的大多数集合类和许多其他类都具有带有apply方法的伴随对象。

For case classes, the Scala compiler automatically creates a companion object with an apply method (as well as other methods). 对于案例类,Scala编译器会自动使用apply方法(以及其他方法)创建伴随对象。

In the scala API documentation , you can access the companion object by clicking on the icon scala API文档中 ,您可以通过单击图标来访问配套对象 对象图标 as explained by Jesper , but you can also switch between a class and its companion object by clicking on the class/object symbol on the top of the main panel: 正如Jesper解释的那样 ,您也可以通过单击主面板顶部的类/对象符号在类及其伴随对象之间切换:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM