- scala> "word" match {
- | case a @ "word" => println(a)
- | case a @ "hi" => println(a)
- | }
- word
this could be changed to:
- scala> "word" match {
- | case a if(a == "word" || a == "hi") => println(a)
- | }
- word
but this is rather verbose. Another option is to use or matching:
- scala> "word" match { case a @ ("word" | "hi") => println(a)}
- word
- /*
- it is possible to provide alternatives in matching
- Anything more advanced needs to be handled with a guard
- See the last examples
- */
- scala> 1 match { case _:Int | _:Double => println("Found it")}
- Found it
- // v will be the value if v is either an Int or a Double
- scala> 1.0 match { case v @ ( _:Int | _:Double) => println(v)}
- 1.0
- // Having variables as part of the patterns is not permitted
- scala> 1.0 match { case v:Int | d:Double => println(v)}
- < console>:5: error: illegal variable in pattern alternative
- 1.0 match { case v:Int | d:Double => println(v)}
- ^
- < console>:5: error: illegal variable in pattern alternative
- 1.0 match { case v:Int | d:Double => println(v)}
- ^
- /*
- Variables are not permitted not even when the name is the same.
- */
- scala> 1.0 match { case d:Int | d:Double => println(d)}
- < console>:5: error: illegal variable in pattern alternative
- 1.0 match { case d:Int | d:Double => println(d)}
- ^
- < console>:5: error: illegal variable in pattern alternative
- 1.0 match { case d:Int | d:Double => println(d)}
- ^
Does line 6 in your example have a typo?
ReplyDeleteIn a recent 2.8, I get
<console>:5: error: not found: value v
Right I had several lines. I copied the wrong line. Thanks.
ReplyDelete