Monday, January 25, 2010

Matching with Or

There is a common case where several expressions in a match statement need to have the same result. For example:

  1. scala> "word" match {
  2.      | case a @ "word" => println(a)
  3.      | case a @ "hi" => println(a)
  4.      | }
  5. word

this could be changed to:
  1. scala> "word" match {               
  2.      | case a if(a == "word" || a == "hi") => println(a)
  3.      | }
  4. word

but this is rather verbose. Another option is to use or matching:
  1. scala> "word" match { case a @ ("word" | "hi") => println(a)}
  2. word


  1. /*
  2. it is possible to provide alternatives in matching
  3. Anything more advanced needs to be handled with a guard
  4. See the last examples
  5. */
  6. scala> 1 match { case _:Int | _:Double => println("Found it")}
  7. Found it
  8. // v will be the value if v is either an Int or a Double
  9. scala> 1.0 match { case v @ ( _:Int | _:Double) => println(v)}
  10. 1.0
  11. // Having variables as part of the patterns is not permitted
  12. scala> 1.0 match { case v:Int | d:Double => println(v)} 
  13. < console>:5: error: illegal variable in pattern alternative
  14.        1.0 match { case v:Int | d:Double => println(v)}
  15.                         ^
  16. < console>:5: error: illegal variable in pattern alternative
  17.        1.0 match { case v:Int | d:Double => println(v)}
  18.                                                     ^
  19. /*
  20. Variables are not permitted not even when the name is the same.
  21. */
  22. scala> 1.0 match { case d:Int | d:Double => println(d)}
  23. < console>:5: error: illegal variable in pattern alternative
  24.        1.0 match { case d:Int | d:Double => println(d)}
  25.                         ^
  26. < console>:5: error: illegal variable in pattern alternative
  27.        1.0 match { case d:Int | d:Double => println(d)}
  28.                                 ^

2 comments:

  1. Does line 6 in your example have a typo?

    In a recent 2.8, I get
    <console>:5: error: not found: value v

    ReplyDelete
  2. Right I had several lines. I copied the wrong line. Thanks.

    ReplyDelete