Skip to content

Instantly share code, notes, and snippets.

@joescii
Last active October 1, 2016 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joescii/192911e990b46366879aaba7568595af to your computer and use it in GitHub Desktop.
Save joescii/192911e990b46366879aaba7568595af to your computer and use it in GitHub Desktop.
Terse syntax for creating an unapply
object UnapplySyntax {
trait Unapplier[A, B] { def unapply(a: A): Option[B] }
class <= [B, A](f: A => Option[B]) extends Unapplier[A, B] {
def unapply(a: A): Option[B] = f(a)
}
object <= {
def apply[B, A](f: A => Option[B]): B <= A = new <=(f)
}
implicit def unapplyConversion[B, A](f: A => Option[B]): B <= A = <=(f)
// Using the class
val I1 = new (Int <= String)(s => Try(s.toInt).toOption)
// Using the apply method
val I2 = <=((s:String) => Try(s.toInt).toOption)
// Implicit conversion
val I3: Int <= String = (s:String) => Try(s.toInt).toOption
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment