long string with only Unicode escapes and possibly newlines in it""" constructing strings "The " + animal1 + " jumped over the " + animal2 "The %s jumped over the %s".format (animal1 , animal2)
= 42 println (s"answer is $answer , dollar is $$") val animal1 = "fox" val animal2 = "dog" println (s"The $animal1 jumped over the $animal2") println (s"One plus one is ${1 + 1}") println (s"The inserted expressions are blocks ${ val x = "!" x * 3 }") answer is 42, dollar is $ The fox jumped over the dog One plus one is 2 The inserted expressions are blocks !!!
println (f"pi ($pi) = $pi %1.3f") val msg = "G’day!" println (f"msg.length = ${msg.length }%5d") pi (3.14159) = 3.142 msg.length = 6 expressions are type-checked against their format specifier f"msg can’t be formatted as $msg %1.3f"
${patn}textn" becomes StringContext ("text0", "text1", ... , "textn").id ( pat1 , ... , patn) id is an extractor object Combine construction and pattern matching together in a single object with both apply and unapply/unapplySeq methods
s : String) e match { case Foo (p1 , p2) => ... } A call Foo.unapply (e) is made which either returns None if e is not matched, or Some ((v1, v2)) if it matches with two pieces v1 and v2. v1 and v2 are recursively matched against p1 and p2
+ 1}") val msg = "The sky is blue" match { case mys"The $thing is $colour" => mys"A $colour thing is $thing" case _ => "no match" } println (msg) One plus one is 2 A blue thing is sky
Use a proper parser to ensure that the interpolation is legal Use a macro to get compile-time checking Convenient for writing programs that manipulate other programs: compilers optimisers static analysis tools staged computation
e match { case exp"1 + 2" => println ("match") case _ => println ("no match") } e match { case exp"$p" => println (s"p=$p") } e match { case exp"$l + $r" => println (s"l=$l r=$r") case _ => println ("no match") } match p=PlusExp(IntExp (1),IntExp (2)) l=IntExp (1) r=IntExp (2)
+ 1;" s match { case stm"a = $e;" => println (s"e=$e") case _ => println ("no match") } s match { case stm"a = $e + 1;" => println (s"e=$e") case _ => println ("no match") } val t = stm"while (1) a = a + 1;" t match { case stm"while ($e) $s" => println (s"e=$e s=$s") case _ => println ("no match") } e=PlusExp(IdnExp(IdnUse(a)),IntExp (1)) e=IdnExp(IdnUse(a)) e=IntExp (1) s=VarAssign(IdnUse(a),PlusExp(IdnExp( IdnUse(a)),IntExp (1)))
be packaged into an easily reusable unit Macro code yet to be fine-tuned More type signatures are needed than we would like Pattern matching relies on a feature of the nightly Scala distribution