gpt4 book ai didi

Scala Trait 如何覆盖派生的 toString Case Class

转载 作者:行者123 更新时间:2023-12-04 10:32:10 27 4
gpt4 key购买 nike

我的背景是 C++/C,我正在尝试学习 Scala。我正在努力理解特征的 toString 方法如何覆盖从特征派生的案例类。当然默认 case 类的 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的具体定义并且是 PC 的基类和 Server ,然后 Computer.toString用来。

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com