How to bind data in heredoc of scala?

2019-07-04 02:22发布

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

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

3条回答
看我几分像从前
2楼-- · 2019-07-04 02:58

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
查看更多
女痞
3楼-- · 2019-07-04 03:01

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)
查看更多
姐就是有狂的资本
4楼-- · 2019-07-04 03:09

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.

查看更多
登录 后发表回答