在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
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
還能夠在插值表達式中使用對象。code
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