concept Player in category scala

appears as: Player, Player
Get Programming with Scala

This is an excerpt from Manning's book Get Programming with Scala.

Because you have declared Player as a class, not as a case class, only its fields marked as val are publicly accessible. You also need to override the function toString: you need to ensure that every time your program converts an instance of Player to text, it must have a human-readable representation. If you forget to do so, the compiler will use the default definition of toString and produce a string similar to “Player@12345”.

Listing 26.4: The object Player and the apply method
// file src/main/scala/org/example/game/entities/Player.scala 
package org.example.game.entities
 
object Player {
 
  // valid example: "Daniela: Spock"
  def apply(text: String): Player =
    text.split(":", 2) match { //#A
      case Array(name, symbol) => //#B
    new Player(name.trim, Symbol.fromString(symbol))
      case _ =>
        val errorMsg = s"Invalid player $text. " +
"Please, use the format <name>: <symbol>"
        throw new IllegalArgumentException(errorMsg)
    }
}

Finally, let’s also define an unapply method for Player so that people can use pattern match on players.

Listing 26.5: The object Player and the unapply method
// file src/main/scala/org/example/game/entities/Player.scala 
package org.example.game.entities
 
object Player {
  
  [...]
 
  def unapply(player: Player): Option[Symbol] = Some(player.symbol) //#A
 
}