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

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

retronym
  • 54,768
  • 12
  • 155
  • 168
Freewind
  • 193,756
  • 157
  • 432
  • 708

3 Answers3

5

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)
Moritz
  • 14,144
  • 2
  • 56
  • 55
  • @Moritz, thank you for your answer. I don't understand why scala not support it heredoc, since they support it in xml – Freewind Jul 26 '10 at 17:47
  • @Freewind in XML literals the curly braces are actually just a fancy syntax for inserting an instance of scala.xml.Text with the string value of the block into the XML nodes. XML is a bit special here but Strings are just Strings to the compiler. – Moritz Jul 26 '10 at 18:05
  • 2
    @Freewind Also see this discussion on why Scala doesn't support string interpolation: http://goo.gl/cJ5u – missingfaktor Jul 26 '10 at 19:15
  • You can also make `format` more Pythonic with an implicit: http://www.bubblefoundry.com/blog/2010/06/fun-with-scala-implicits/ – pr1001 Jul 26 '10 at 21:34
  • @Rahuλ G, I can't open the http://goo.gl/cJ5u, but I want to see it much. Can you open it ? – Freewind Jul 27 '10 at 04:51
  • 2
    @Freewind, Yes, I am able to open it. You can try this direct link if the shortened URL isn't working: http://scala-programming-language.1934581.n4.nabble.com/Why-Martin-hates-string-interpolation-Was-Re-Formatting-Questions-Summary-td2008748.html – missingfaktor Jul 27 '10 at 12:31
  • @Rahuλ G, it's very interesting. Is really because of keyboard? – Freewind Jul 27 '10 at 13:29
  • @Freewind, As he himself clarified in the discussion, Odersky uses a US keyboard. So this Swiss keyboard theory is obviously wrong. :) – missingfaktor Jul 27 '10 at 13:33
  • @Rahuλ, yes :) So, the true reason is a secret – Freewind Jul 27 '10 at 13:48
  • 1
    This is outdated! String interpolation exists in scala, refer to @javabda's answer: http://stackoverflow.com/a/23875645/5214346 – Jean Bob May 19 '17 at 09:56
5

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.

pr1001
  • 21,727
  • 17
  • 79
  • 125
4

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
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560