Showing posts with label b4253| `` (Back Tick). Show all posts
Showing posts with label b4253| `` (Back Tick). Show all posts

Patter Matching Values, Variables & Types

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

Reserved Keywords

PS : 51
Some Java methods(Example : java.util.Scanner.match) are reserved keywords in Scala. Use back-ticks(``) to specify those method names.

scala> import java.util.Scanner
import java.util.Scanner

scala> val scanner:Scanner = new Scanner("This is a demo")
scanner: java.util.Scanner = java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]

scala> scanner.hasNext("This")
res57: Boolean = true

scala> // 'match' is a reserved keyword and will throw error

scala> scanner.match()
<console>:1: error: identifier expected but 'match' found.
       scanner.match()
               ^
<console>:1: error: '{' expected but '(' found.
       scanner.match()
                    ^

scala> // Backtick is used around the keyword 'match'

scala> scanner.`match`()
res58: java.util.regex.MatchResult = java.util.regex.Matcher[pattern=This region=0,14 lastmatch=This]