Last active
August 29, 2015 14:06
-
-
Save mslinn/ba573f9c8d6068af8d19 to your computer and use it in GitHub Desktop.
Extends Java enums so Scala match statements work. The purpose of this code example is to show a generic way of extending multiple Java enums in a Scala program so Scala match statements work, while preserving all of the functionality of Java enums for use by Scala programs. That is why there are methods that are defined but not used. A macro co…
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
object BlendedEnums extends App { | |
import Day._ | |
trait EnumLike[T] extends Ordered[T] { | |
def name: String | |
def compare(other: T): Int | |
def ordinal: Int | |
def toString: String | |
} | |
sealed class CaseDay(val day: Day) extends EnumLike[Day] { | |
lazy val name: String = day.name | |
def compare(other: Day): Int = day.compareTo(other) | |
lazy val ordinal: Int = day.ordinal | |
override lazy val toString = day.toString | |
} | |
object CaseDay { | |
import scala.collection.immutable.{SortedSet, TreeSet} | |
case object Monday extends CaseDay(MONDAY) | |
case object Tuesday extends CaseDay(TUESDAY) | |
case object Wednesday extends CaseDay(WEDNESDAY) | |
case object Thursday extends CaseDay(THURSDAY) | |
case object Friday extends CaseDay(FRIDAY) | |
case object Saturday extends CaseDay(SATURDAY) | |
case object Sunday extends CaseDay(SUNDAY) | |
def valueOf(name: String) = Day.valueOf(name) | |
type CaseDayObject = CaseDay with Product with Serializable | |
lazy val values: SortedSet[CaseDayObject] = { | |
val ordering = Ordering.by { caseDayObject: CaseDayObject ⇒ caseDayObject.ordinal } | |
TreeSet(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)(ordering) | |
} | |
} | |
import CaseDay._ | |
def tellItLikeItIs(theDay: CaseDay): Unit = { | |
val msg = theDay match { | |
case Monday => "Mondays are bad." | |
case Friday => "Fridays are better." | |
case Saturday => "Weekends are best." | |
case Sunday => "Weekends are best." | |
case _ => "Midweek days are so-so." | |
} | |
println(msg) | |
} | |
tellItLikeItIs(Monday) | |
tellItLikeItIs(Tuesday) | |
tellItLikeItIs(Wednesday) | |
tellItLikeItIs(Sunday) | |
} |
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
public enum Day { | |
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment