我的背景是 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 fromAnyRef
. 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 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60364713/