Scala:伴随对象的目的 [英] Scala: companion object purpose

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

问题描述


可能重复:

感谢对我之前发布的所有回复( Scala:随播广告对象和新关键字)。我想问一下Scala中一个伴随对象的一般目的是什么?
首先,我们可以不包括所有的方法,如apply,在类本身的contructor /方法定义的形式?
此外,一个伴随布尔对象的要点是什么,因为它甚至没有定义apply方法?

Thanks for all responses to my previous post( Scala: companion objects and "new" keyword). I would like to ask you what is the general purpose of a companion object in Scala? Firstly, could we not have included all the methods, such as apply, in the forms of contructor/method definition on the class itself? Furthermore, what is the point of a companion Boolean object, as it does not even define apply method?

再次感谢您的所有回复。

Thanks again in advance for all your responses.

推荐答案

需要配对对象:


  • 声明与伴侣的类相关的方法,否则它将是静态的(与在Java中不同,您不能在Scala中的类本身中声明一个静态方法)

  • 声明 unapply unapplySeq 方法来定义模式匹配的自定义提取器(参见 here

  • 声明通常用作工厂方法的 apply 创建特定类的对象(但不一定是)

  • 伴随对象可以访问其伴随trait /类的私有字段和方法 - 可用于在特定特征上创建静态操作/ class

  • 它们对于隐式解析很重要 - 对于某种类型的隐式值,检查该类型的伴随对象以查看是否存在对应的隐含定义;请参阅 Scala规范中的隐式解析的确切规则或此博文

  • declare methods related to the companion's class which would otherwise be static (unlike in Java, you cannot declare a static method within the class itself in Scala)
  • declare the unapply and unapplySeq methods to define custom extractors for pattern matching (see here)
  • declare the apply method which is typically used as a factory method that creates objects of the particular class (but doesn't have to be)
  • companion objects can access private fields and methods of their companion trait/class - useful for creating static operations on that particular trait/class
  • they are important for the implicit resolution -- when looking for an implicit value of a certain type, the companion object of that type is inspected to see if there exists a corresponding implicit definition; see the exact rules of implicit resolution in the Scala specification or a short summary in this blog post

Scala标准库中的 Boolean 对象提供了 unbox 用于在原始布尔与其包装的对象表示之间进行转换。它还是(目前)用作 @specialized 注释的参数,用于表示类需要专用于哪些基本类型。

The Boolean object in the Scala standard library provides the methods box and unbox used to convert between primitive booleans and their wrapped, object representations. It is additionally (currently) used as an argument to the @specialized annotation, to denote on which primitive types the class needs to be specialized on.

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

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