String Interpolation
String interpolation lets you drop values right into a sentence, like filling blanks in a story as you write it. You put a dollar sign in front of the name and Scala fills it in.
In this page:
Syntax
val name = "value"
println(s"text $name more text")
println(s"sum: ${expression}")
String Interpolation
The s"..." interpolator embeds expressions in a string with $name or ${expression}. The f"..." interpolator adds printf-style formatting, like f"$price%.2f" for two decimal places.
The raw"..." interpolator disables escape sequence processing, so raw"\n" stays as the literal two characters backslash-n instead of becoming a newline.
Note:
Use f-interpolation, like f"$price%.2f", whenever you need precise numeric formatting instead of the default toString.
Example: String Interpolation
object Main extends App {
val name = "Ruby"
val price = 19.5
println(s"Hello, $name!")
println(f"Price: $price%.2f")
println(raw"Raw newline stays literal: \n")
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting the
sbefore the quotes, as in"Hello, $name!", which prints$nameliterally. - Writing
s"$price%.2f"and expecting formatting, when onlyf"$price%.2f"applies the format. - Using
$obj.fieldand getting the wrong result, when an expression needs braces such as${obj.field}.
Chapter Summary
valdeclares immutable values andvardeclares mutable ones.- Scala has types such as
Int,Double,Boolean,Char, andString, and the compiler can often infer them. Unitand string interpolation round out the basics.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: