2

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);
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Greedo
  • 23
  • 3
  • 1
    To go with Mario's answer, possibly checkout [this question](https://stackoverflow.com/questions/27465951/how-to-avoid-scalas-case-class-default-tostring-function-being-overridden) – Andrew Nolan Feb 23 '20 at 17:23
  • It may be worth to mention that in general, a **trait** shouldn't provide `toString` unless you are completely sure you want that for every subtype _(and thus I would make it `final`)_. - Also, many people would argue that you shouldn't really in `toString` at all for nothing but quick debugging, create your own method if you need to turn an object into an Strting. – Luis Miguel Mejía Suárez Feb 23 '20 at 17:28

1 Answers1

2

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.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98