Search code examples
scalaoverridingtraitstostringcase-class

Scala How can Trait override toString Case Class that is Derived Off


My background is in C++/C and I am trying to learn scala. I am struggling to understand how a trait's toString method overrides case class derived from the trait. Surely the default case class's toString method should over ride the trait's? I am missing something obvious?

Code

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);

Solution

  • SLS is clear on this point

    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.

    Hece because trait Computer provides concrete definition of toString and is a base class of PC and Server, then Computer.toString is used.