将变量打印为多行字符串的一部分?

时间:2014-07-09 20:38:47

标签: scala

val name = "Cory"
"""
  |Hi! My name is " + name + " how are you?
""".stripMargin

部分+ name +不会被解释为代码,而是解释为文本。如何在多行字符串中打印变量的值?

1 个答案:

答案 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"..."是最简单的。