When using match case, specific matching should appear before general mapping. In case clause, a word that start with a lowercase letter is considered as a new Variable. A word that starts with an Uppercase letter is considered to be a Type
//#PS:101
//psn > a40 > a20
scala> val mylist = Seq(3, 4, 5, 5.5, "mystring", "2ndstring",
| 1.7, 'something, true)
mylist: Seq[Any] = List(3, 4, 5, 5.5, mystring, 2ndstring, 1.7, 'something, true)
scala> val mydata = 4
mydata: Int = 4
scala> for ( data <- mylist){
| val mystr = data match {
| case 3 => s"Matches Integer '3'"
| //External variables are referred with backtick(``).
| //***Note : Not using `backtick`(like case mydata) is like a
| // catch all option
| case `mydata` => s"Matches mydata '4'"
| // A word that start with an Upper case(Int here...) is considered
| // to be a Type
| case Int | _:Boolean
| => s"Matches any Integer/Boolean : $data"
| case "mystring" => s"Matches String 'mystring'"
| case _:String => s"Matches any string : $data"
| // As no type is given, Any is inferred
| case _ => s"Matches others : $data"
| }
| println(mystr)
| }
Matches Integer '3'
Matches mydata '4'
Matches others : 5
Matches others : 5.5
Matches String 'mystring'
Matches any string : 2ndstring
Matches others : 1.7
Matches others : 'something
Matches any Integer/Boolean : true
No comments:
Post a Comment