val name = "Cory"
"""
|Hi! My name is " + name + " how are you?
""".stripMargin
部分+ name +
不会被解释为代码,而是解释为文本。如何在多行字符串中打印变量的值?
答案 0 :(得分:9)
如果您使用的是2.10或更高版本,则可以使用字符串插值:
scala> s"""
| |Hi! My name is $name how are you?
| """.stripMargin
res0: String =
"
Hi! My name is Cory how are you?
"
对于2.9或更早的版本,你会遇到类似这样的事情:
scala> ("""
| |Hi! My name is """ + name + """ how are you?
| """).stripMargin
res1: String =
"
Hi! My name is Cory how are you?
"
请注意,Scala中有several flavors of string interpolation - s"..."
是最简单的。