Last active
November 9, 2015 23:09
-
-
Save trane/56a83b936eecff9877cc to your computer and use it in GitHub Desktop.
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
// define the ADT | |
trait Tag { | |
val id: Byte | |
} | |
case object Empty extends Tag { | |
val id = -1.toByte | |
} | |
case object Initial extends Tag { | |
val id = 0.toByte | |
} | |
case object Authenticated extends Tag { | |
val id = 1.toByte | |
} | |
// create a smart constructor | |
object Tag { | |
def apply(id: Byte): Tag = id match { | |
case 0 => Initial | |
case 1 => Authenticated | |
case _ => Empty | |
} | |
} | |
// here is a partial function that acts like a finagle filter | |
val TagFilter: PartialFunction[Tag, String] = { | |
case Authenticated => "auth" | |
case Initial => "login" | |
case _ => "unknown" | |
} | |
// here is are some incoming tag ids | |
println(TagFilter(Tag(0.toByte))) // login | |
println(TagFilter(Tag(1.toByte))) // auth | |
println(TagFilter(Tag(2.toByte))) // unknown | |
// here is the great part | |
// now you can define interfaces that *only* accept a specific Tag type! | |
val authedFilter: Authenticated.type => String = t => "you are authenticated!!!!" | |
println(authedFilter(Authenticated)) // you are authenticated!!!! | |
//println(authedFilter(Empty)) // !! DOES NOT COMPILE !! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment