Note. If a match is not found a scala.MatchError is thrown
- scala> val s = "sampleString"
- s: java.lang.String = sampleString
- scala> s match {
- | case "sampleString" => "its a match!"
- | case _ => "no match"
- | }
- res0: java.lang.String = its a match!
- scala> s match {
- | case m @ "sampleString" => "its a match!"
- | case _ => "no match"
- | }
- res1: java.lang.String = its a match!
- scala> s match {
- | case m @ "sampleString" => "we found "+m+"!"
- | case _ => "no match"
- | }
- res2: java.lang.String = we found sampleString!
- scala> s match {
- | case m if(m.startsWith("s") ) => "its a match!"
- | case _ => "no match"
- | }
- res3: java.lang.String = its a match!
- scala> s match {
- | case m => "this matches everything"
- | }
- res4: java.lang.String = this matches everything
- scala> val obj:Any = s // I am assigning s to a variable whose type is Any (parent of all object).
- obj: Any = sampleString
- scala> obj match {
- | case string:String => "we found a string"
- | case integer:Int => "we found an integer"
- | case _ => "hmmm don't know what it is"
- | }
- res6: java.lang.String = we found a string
- scala> // Now we will see what happens when a match fails
- scala> obj match {
- | case integer:Int => "we found an integer"
- | case double:Double => "we found an double"
- | }
- scala.MatchError: sampleString
- at .
(:7) - at .
() - at RequestResult$.
(:3) - at RequestResult$.
() - at RequestResult$result(
) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.i...
- scala>
Hi,
ReplyDeleteIt is better to add some explanation rather than just giving code snippet. For example what is the difference between case "sampleString" and case m @ "sampleString".
Thanks,
Senthil
m is name for whole matching term which can have many parts.
ReplyDeleteQuestion is still opened.
ReplyDeleteWhat m @ "sampleString" means?
The difference between
ReplyDeletecase "sampleString" => ...
and
case m @ "sampleString" => ...
is that "sampleString" is assigned to m. In this example it is not too useful but consider the code:
functionThatReturnsList() match {
case m @ "s1" :: "s2" :: "s3" :: _* => // use m
case _ => // no match
}
so in this case we don't have to assign *functionThatReturnsList()* to a val since that assignment is inline within the case call.