kmeredith (21) [Avatar] Offline
MEAP version 6's page 96 shows:

sealed trait DayOfWeek { 
  val value: Int
  override def toString = value match {
    case 1 => "Monday"
    case 2 => "Tuesday"
    case 3 => "Wednesday"
    case 4 => "Thursday"
    case 5 => "Friday"
    case 6 => "Saturday"
    case 7 => "Sunday"

object DayOfWeek { #B
  private def unsafeDayOfWeek(d: Int) = new DayOfWeek { val value = d }
  private val isValid: Int => Boolean = { i => i >= 1 && i <= 7 }
  def dayOfWeek(d: Int): Option[DayOfWeek] = if (isValid(d))
    Some(unsafeDayOfWeek(d)) else None #C

I'm curious why an unsafe method, i.e. due to the inexhaustive pattern match, shows up in DayOfWeek#toString.

In the previous chapter, you clearly explained the values of using Algebraic Data Types. This partial function, toString, does not enjoy the benefits of an ADT.


By the way, your explanation of lenses was very clear! I had watched videos previously that explained Lenses, but I did not understand them entirely until reading your book.
Debasish Ghosh (111) [Avatar] Offline
DayOfTheWeek's method toString is unsafe and that's clearly mentioned in the text. Hence we have the smart constructor method in the companion object named dayOfWeek which should be used to construct a valid DayOfWeek. That's the precise purpose of a smart constructor. All other methods in the companion object are private and hence not accessible to the user.

Also you mention about ADT. We don't have any algebraic data type here. trait DayOfWeek is merely a module that abstracts some logic.

Let me know if this clarifies your question.