案例类和伴随对象 [英] Case class and companion object

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

问题描述

我在正确理解类及其伴生对象的使用方面有问题.

I have problems understanding correctly the use of class and their companion object.

在定义case类的时候有它的伴生对象,但是定义一个和case类同名的对象会有什么结果呢?它是否覆盖了伴随对象?以及如何访问案例类参数?

When defining a case class there is its companion object that comes with it, but what is the result of defining an object having the same name as the case class? Does it override the companion object? And how to access case class parameters?

例如在 TestCaseClass.scala 文件中,我定义了以下内容:

For example in TestCaseClass.scala file I define the following :

case class TestCaseClass(att1: String, att2: Int, att4s: List[String])

object TestCaseClass {

  def iWantDoSomethingWithMyParams: String = {
    att1 + " " + att2
  }

  // Other functions
}

object AnotherTestCaseClass {

  def iWantDoSomethingWithTestCaseClassParams: String = {
  // How to access TestCaseClass.att1
    TestCaseClass.att1 + " " + TestCaseClass.att2
  }

  def iWantGetAllAttr4: List[String] = {
     // ???
  }
}

推荐答案

在某种程度上,赋予 objectclass 相同的名称(或 trait) 只是一个约定问题.但它也有一些特殊的意义.

To some extent, giving an object the same name as a class (or trait) is just a matter of convention. But it also has a bit of special meaning.

伴随对象是一个单例类,就像任何其他对象一样.如果您希望伴随对象中的方法与类的实例交互,则必须像在任何其他情况下一样向它传递类的实例.因此,要修复您的第一个示例:

The companion object is a singleton class just like any other object. If you want a method in the companion object to interact with an instance of the class, you have to pass it an instance of the class just like in any other situation. So, to fix your first example:

case class TestCaseClass(att1: String, att2: Int, att4s: List[String])

object TestCaseClass {    
  def iWantDoSomethingWithMyParams(x: TestCaseClass): String =
    x.att1 + " " + x.att2
}

类和对象不会以任何方式覆盖"或踩到彼此的脚趾,因为类和对象属于不同的命名空间.类名称用于类型级别(以及构造函数调用),对象名称用于术语级别.

The class and the object do not "override" or step on each other's toes in any way because classes and objects belong to different namespaces. Class names are used at the type level (and also in constructor calls), and object names are used at the term level.

类与其同伴之间存在一些关系:

There are a few relationships between a class and its companion:

  • 它确实会影响隐式的解析方式 - 在类的伴随对象中定义的任何隐式都会自动进入作用域.

  • It does affect how implicits are resolved - Any implicts defined in a class's companion object are automatically brought into scope.

private 类的成员对对象可见,反之亦然.

private members of the class are visible to the object, and vice versa.

Case classes 有点不同,因为 case class 实际上是一个简写,除了定义一个 class 之外,还增加了 applyunapply 方法对其伴随对象.

Case classes are a little bit different, because case class is actually a shorthand which, in addition to defining a class, also adds apply and unapply methods to its companion object.

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

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