在以下示例中,我需要变量x2
结束时使用值my name is Paul
而不是my name is $name
,这可能吗?
scala> val name = "Paul"
name: String = Paul
scala> val xxx = s"my name is $name"
xxx: String = my name is Paul
scala> val x1 = "my name is $name"
x1: String = my name is $name
scala> val x2 = s"" + x1
x2: String = my name is $name
答案 0 :(得分:5)
字符串插值不适合这里,因为您要格式化现有字符串。您想使用字符串的C样式格式:
println("my name is %s".format("paul"))
如果你想(尽管我没有理由),你可以直接使用StringContext
:
scala> val name = "paul"
name: String = paul
scala> StringContext("My name is ", "").s(name)
res1: String = My name is paul
答案 1 :(得分:1)
这有效:
scala> val x4 = "my name is %s"
x4: String = my name is %s
scala> x4.format("Paul")
res3: String = my name is Paul