Created
January 14, 2018 19:31
-
-
Save zapidan/91669ae58f6863011d7a1fe800a6e840 to your computer and use it in GitHub Desktop.
scala enums
This file contains hidden or 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
import Test.{doWhat, findColorById, findColorById2, findColorByName} | |
import TrafficLightColorById.{Green, Red, TrafficLightColorById, Yellow} | |
import scala.util.Try | |
/* | |
Enums (id, name) with default id incremental | |
*/ | |
object TrafficLightColor extends Enumeration { | |
val Red = Value(0, "RED") | |
val Yellow = Value(10) | |
val Green = Value("GREEN") | |
} | |
/* | |
Add type alias so type of enum is TrafficLightColorById.TrafficLightColorById | |
(need to import all members of TrafficLightColorById._) | |
*/ | |
object TrafficLightColorById extends Enumeration { | |
type TrafficLightColorById = Value | |
val Red = Value(0, "dark red") | |
val Yellow = Value(22, "egg yellow") | |
val Green = Value(333, "green as an alien") | |
} | |
object Test { | |
println(classOf[TrafficLightColor.Value]) | |
def findColorByName(color: String) = { | |
val enum: Try[TrafficLightColor.Value] = Try(TrafficLightColor.withName(color.toUpperCase())) | |
enum.getOrElse("not defined") | |
} | |
def findColorById(id: Int) = { | |
val enum: Try[TrafficLightColorById] = Try(TrafficLightColorById(id)) | |
enum.getOrElse("not defined") | |
} | |
def findColorById2(id: Int): Option[TrafficLightColorById] = { | |
val enum = Try(TrafficLightColorById(id)) | |
if (enum.isSuccess) { | |
Some(enum.get) | |
} else { | |
None | |
} | |
} | |
def doWhat(color: TrafficLightColorById): String = { | |
color match { | |
case Red => "STOP" | |
case Yellow => "hurry up" | |
case Green => "GO" | |
case _ => "undefined" | |
} | |
} | |
} | |
object Client extends App { | |
println(findColorByName("Red")) | |
println(findColorByName("red")) | |
println(findColorByName("Green")) | |
println(findColorByName("GREEN")) | |
println(findColorByName("Yellow")) | |
println(TrafficLightColor(10)) | |
println(TrafficLightColorById(0)) | |
println(TrafficLightColorById(22)) | |
println(TrafficLightColorById(333)) | |
println(findColorById(444)) | |
println(doWhat(Red)) | |
println(doWhat(Green)) | |
println(doWhat(Yellow)) | |
println(doWhat(null)) | |
println(doWhat(findColorById2(123).getOrElse(null))) | |
println(doWhat(findColorById2(333).getOrElse(null))) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment