在Scala中使用字符串插值函数,需要再字符串前加上字符"s",然后再字符串中的每个插值变量前加上“$”符号。
scala> val name = "Fred"
name: String = Fred
scala> val age = 18
age: Int = 18
scala> val weight = "200"
weight: String = 200
scala> println(s"$name is $age years old, and weights $weight pounds")
Fred is 18 years old, and weights 200 pounds
除了可以使用变量外还可以在字符串插值中使用表达式代码。
scala> println(s"$age next year is ${age + 1}")
18 next year is 19
scala> println(s"$age is 18: ${age == 18}")
18 is 18: true
还可以在插值表达式中使用对象。
scala> println(s"${student.name} is ${student.age} age years old.")
Fred is 18 age years old.
Scala为我们提供了更多的字符串插值函数,比如使用"f"可以对插值打印格式进行控制,比如保留两位小数。
scala> val weight = 200
weight: Int = 200
scala> println(f"$name is $age years old, and weights $weight%.2f pounds")
Fred is 18 years old, and weights 200.00 pounds
插值函数"raw"能够让转义字符失去意义。
scala> "a\nb"
res28: String =
a
b
scala> raw"a\nb"
res29: String = a\nb
来源:oschina
链接:https://my.oschina.net/u/2633112/blog/800096