Skip to content

Instantly share code, notes, and snippets.

@trane
Last active November 9, 2015 23:09
Show Gist options
  • Save trane/56a83b936eecff9877cc to your computer and use it in GitHub Desktop.
Save trane/56a83b936eecff9877cc to your computer and use it in GitHub Desktop.
// 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