Last active
October 1, 2016 20:46
-
-
Save joescii/192911e990b46366879aaba7568595af to your computer and use it in GitHub Desktop.
Terse syntax for creating an unapply
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
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