且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scala:伴随对象的目的

更新时间:2022-02-05 08:00:17

需要配对对象:


  • 声明与伴侣的类相关的方法,否则它将是静态的(与在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.