Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Last active February 7, 2017 18:38
Show Gist options
  • Save manjuraj/6d66a94e3d71fbd0e60e to your computer and use it in GitHub Desktop.
Save manjuraj/6d66a94e3d71fbd0e60e to your computer and use it in GitHub Desktop.
Boolean unapply extractor
// A boolean extractor is an object that returns Boolean from
// the unapply method rather than Option[_].
scala> :paste
object HasVowels {
def unapply(in: String): Boolean = in.exists("aeiou".toSet)
}
// Exiting paste mode, now interpreting.
defined module HasVowels
scala> :paste
// Note that HasVowels() has ()
// This is critical because otherwise the match checks whether
// the input is the HasVowels object.
// The () forces the unapply method to be used for matching
scala> :paste
"hello world" match {
case HasVowels() => println("Vowel found")
case _ => println("No Vowels")
}
// Exiting paste mode, now interpreting.
Vowel found
scala> :paste
class HasChar(c: Char) {
def unapply(in: String) = in.contains(c)
}
object HasChar {
def apply(c: Char) = new HasChar(c)
}
val HasC = HasChar('c')
// Exiting paste mode, now interpreting.
defined class HasChar
defined module HasChar
HasC: HasChar = HasChar@45d682e8
scala> :paste
"It actually work!" match {
case HasC() => println("a 'c' was found")
case _ => println("no c was found")
}
a 'c' was found
// Exiting paste mode, now interpreting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment