Skip to content

Instantly share code, notes, and snippets.

@timperrett
Forked from viktorklang/Concise value types
Created July 6, 2009 14:14
Show Gist options
  • Save timperrett/141447 to your computer and use it in GitHub Desktop.
Save timperrett/141447 to your computer and use it in GitHub Desktop.
object ValueTypes6
{
abstract class Type[T](val p : (T) => boolean)
{
sealed protected[Type] case class X[T] protected[Type] (val value : T)
type Type = X[T]
def apply(t : T) : Option[Type] = if(p(t)) Some(mk(t)) else None
def unapply(v : Type) : Option[T] = if(v == null) None else Some(v.value)
private def mk(t : T) : Type = X(t)
}
object Zipcode extends Type[String](_.length > 0)
object City extends Type[String](_.length > 4)
case class Foo(val zipcode : Zipcode.Type, val city : City.Type)
def main(a : Array[String]) : Unit = {
val x = for(
z <- Zipcode("foo");
c <- City("bartown")) yield Foo(z,c);
x.map( _ match { case Foo(Zipcode(x),City(y)) => println("blipp: " + x + " " + y);
case x => println(x)} )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment