Created
July 10, 2015 18:18
-
-
Save yujikiriki/c9f14b626b05975c85b6 to your computer and use it in GitHub Desktop.
ShapelessEnum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A safer ADT+shapeless alternative ... | |
// | |
object ShapelessEnumDemo extends App { | |
// ADT as an enumeration. Barely any more boilerplate ... | |
sealed trait WeekDay | |
object WeekDay { | |
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = new WeekDay {} | |
val values: Set[WeekDay] = Values | |
} | |
import WeekDay._ | |
def isWorkingDay(d: WeekDay) = ! (d == Sat || d == Sun) | |
assert((WeekDay.values filter isWorkingDay) == Set(Mon, Tue, Wed, Thu, Fri)) | |
// ... the payoff ... | |
def isWeekend(d: WeekDay) = d match { | |
case Sat | Sun => true | |
case _ => false // compile time non-exhaustive match warning/error without this case | |
} | |
assert(!isWeekend(Mon)) // | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment