Scala: How to write a toString method in a trait/class (inheritance)

If you need to override toString when creating a Scala class or class hierarchy (using inheritance), you can override toString like this:

trait CrewMember {
    override def toString: String = this.getClass.getName
}
class Officer extends CrewMember

If you paste that code into the Scala REPL you can then run a little experiment like this:

scala> val o = new Officer
o: Officer = Officer

scala> o
res0: Officer = Officer

As shown in both instances, the toString method in the parent trait results in the class name being printed by the toString method. While I’m in the neighborhood, don’t forget that these name-related methods are available when you call getClass:

  • getName
  • getCanonicalName
  • getSimpleName
  • getTypeName

It may be possible that you’ll need to implement your Scala toString method differently than I’ve shown when you use multiple levels of inheritance, but for a simple example like this, this approach works.