Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created July 23, 2016 14:15
Show Gist options
  • Save JoolsF/3ead795d2fa41621400bb1dec6b2117c to your computer and use it in GitHub Desktop.
Save JoolsF/3ead795d2fa41621400bb1dec6b2117c to your computer and use it in GitHub Desktop.
UnapplySeq Example
/**
* For regular parameters / fixed arity these are the apply constructs and unapply de-structures:
*/
object S {
def apply(a: A):S = ... // makes a S from an A
def unapply(s: S): Option[A] = ... // retrieve the A from the S
}
val s = S(a)
s match { case S(a) => a }
/**
* For repeated parameters / variable arity these are the apply constructs and unapplySeq de-structures:
*/
object M {
def apply(a: A*): M = ......... // makes a M from an As.
def unapplySeq(m: M): Option[Seq[A]] = ... // retrieve the As from the M
}
val m = M(a1, a2, a3)
m match { case M(a1, a2, a3) => ... }
m match { case M(a, as @ _*) => ... }
//For example...
object Names {
def unapplySeq(name: String): Option[(String, String, Array[String])] = {
val names = name.trim.split(" ")
if (names.size < 2) None
else Some((names.last, names.head, names.drop(1).dropRight(1)))
}
}
def greet(fullName: String) = fullName match {
case Names(lastName, firstName, a) => "Good morning, " + firstName + " " + lastName + "!"
case _ => "Welcome! Please make sure to fill in your name!"
}
greet("John Michael Doe") // res0: String = Good morning, John Doe!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment