Thursday, October 29, 2009

Boolean Extractors

As discussed in other topics there are several ways to create custom extractors for objects. See
There is one more custom extractor that can be defined. Simple boolean extractors. They are used as follows:
  1. scala>"hello world"match {                   
  2.      | case HasVowels() => println("Vowel found")
  3.      | case _ => println("No Vowels")            
  4.      | }
  5. Vowel found

A boolean extractor is an object that returns Boolean from the unapply method rather than Option[_].

Examples:
  1. scala>object HasVowels{ defunapply(in:String):Boolean = in.exists( "aeiou" contains _ ) }
  2. defined module HasVowels
  3. // Note that HasVowels() has ().
  4. // This is critical because otherwise the match checks whether
  5. // the input is the HasVowels object.
  6. // The () forces the unapply method to be used for matching
  7. scala>"hello world"match {
  8.      | case HasVowels() => println("Vowel found")
  9.      | case _ => println("No Vowels")
  10.      | }
  11. Vowel found
  12. // Don't forget the ()
  13. scala>"kkkkkk"match {    
  14.      | case HasVowels() => println("Vowel found")
  15.      | case _ => println("No Vowels")
  16.      | }
  17. No Vowels
  18. scala>class HasChar(c:Char) {           
  19.      | defunapply(in:String) = in.contains(c)
  20.      | }
  21. defined class HasChar
  22. scala>val HasC = new HasChar('c')
  23. HasC: HasChar = HasChar@3f2f529b
  24. // Don't forget the () it is required here as well
  25. scala>"It actually works!"match {
  26.      | case HasC() => println("a c was found")
  27.      | case _ => println("no c found")  
  28.      | }
  29. a c was found
  30. // Don't forget the ()
  31. scala>"hello world"match { 
  32.      | case HasC() => println("a c was found")
  33.      | case _ => println("no c found")       
  34.      | }
  35. no c found

No comments:

Post a Comment