How to bind data in heredoc of scala?

爷,独闯天下 提交于 2019-12-10 18:47:20

问题


val name = "mike"
val str = """Hi, {name}!"""
println(str)

I want it output the str as Hi, mike!, but failed. How to do this?


回答1:


Scala does not support string interpolation. There is a compiler plugin that implements it at http://github.com/jrudolph/scala-enhanced-strings.

Without the plugin you can use concatenation or format strings:

val str = name formatted "Hi, %s!"

or of course

val str = "Hi, %s!".format(name)



回答2:


A total hackish solution would be to use Scala's XML interpolation:

val name = "Mike"
val str = <a>Hi, {name}!</a> text

The text method returns string contents of an XML construct, so our tags are stripped.




回答3:


As of scala >= 2.10 string interpolations are supported:

val str = "Foo Bar"
str: String = Foo Bar

scala> s"Interpolating: $str"
res0: String = Interpolating: Foo Bar


来源:https://stackoverflow.com/questions/3337152/how-to-bind-data-in-heredoc-of-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!