Scala Trait 如何重写派生的 toString Case 类

标签 scala overriding traits tostring case-class

我的背景是 C++/C,我正在尝试学习 scala。我正在努力理解特征的 toString 方法如何覆盖从该特征派生的案例类。当然默认案例类的 toString 方法应该覆盖特征的方法吗?我遗漏了一些明显的东西?

代码

trait Computer {
  def ram: String
  def hdd: String
  def cpu: String

  override def toString = "RAM= " + ram + ", HDD=" + hdd + ", CPU=" + cpu

}

private case class PC(ram: String, hdd: String, cpu: String) extends Computer 

private case class Server(ram: String, hdd: String, cpu: String) extends Computer

object ComputerFactory {
  def apply(compType: String, ram: String, hdd: String, cpu: String) = compType.toUpperCase match {
    case "PC" => PC(ram, hdd, cpu)
    case "SERVER" => Server(ram, hdd, cpu)
  }
}
val pc = ComputerFactory("pc", "2 GB", "500 GB", "2.4 GHz");
val server = ComputerFactory("server", "16 GB", "1 TB", "2.9 GHz");

println("Factory PC Config::" + pc);
println("Factory Server Config::" + server);

最佳答案

SLS这点很明确

Every case class implicitly overrides some method definitions of class scala.AnyRef unless a definition of the same method is already given in the case class itself or a concrete definition of the same method is given in some base class of the case class different from AnyRef. In particular:

Method toString: String returns a string representation which contains the name of the class and its elements.

因此,因为trait Computer提供了toString的具体定义,并且是PCServer的基类,然后使用Computer.toString

关于Scala Trait 如何重写派生的 toString Case 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60364713/

相关文章:

ios - 为什么重写prepareForSegue会显示重写只能在类成员上指定

rust - 为什么 io::copy 要求读者和作者都是可变引用?

struct - 如何克隆存储盒装特征对象的结构?

scala - 使用 scalamock 在 scala 中使用 ClassTag 的模拟方法

scala - 在 Gatling 中请求超时

java - 如何覆盖对象的ArrayList的ToString方法?

java - 重写 equals 方法会出错

performance - 如何将 Iterable[String, String, String] 转换为 DataFrame?

scala - Scala中最简单的过程通讯形式

c++ - C++ 是否有类似 scala 的 mixin?