There are three kinds of interpolated strings.
- A String of the form
s"foo ${bar}"
will have the value of expressionbar
, converted to aString
and inserted in place of${bar}
. If the expressionbar
returns an instance of a type other thanString
, atoString
method will be invoked, if one exists. It is an error if it can’t be converted to aString
. - The second kind provides
printf
formatting and uses the prefixf
. - The third kind is called “raw” interpolated strings. It doesn’t expand escape characters, like
\n
.
code example
// The first way:
val name: String = "BrownWong"
println(s"My name is ${name}")
println(s"My name is $name") // 省略大括号
// The second way:
val money = 100F
println(f"I have ${money}%.2f $$") // "$$"输出"$"
println(f"I have $money%.2f $$")
println("I have %.2f $".format(money)) // 用字符串的format函数同样可以实现
// The third way:
println(raw"haha\nhaha")
output:
My name is BrownWong
My name is BrownWong
I have 100.00 $
I have 100.00 $
I have 100.00 $
haha\nhaha
Ref