The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

kmeredith (23) [Avatar] Offline
#1
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.

P.S.

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 (116) [Avatar] Offline
#2
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.

Thanks.