views:

110

answers:

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

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

+6  A: 

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
@Moritz, thank you for your answer. I don't understand why scala not support it heredoc, since they support it in xml
Freewind
@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
@Freewind Also see this discussion on why Scala doesn't support string interpolation: http://goo.gl/cJ5u
missingfaktor
You can also make `format` more Pythonic with an implicit: http://www.bubblefoundry.com/blog/2010/06/fun-with-scala-implicits/
pr1001
@Rahuλ G, I can't open the http://goo.gl/cJ5u, but I want to see it much. Can you open it ?
Freewind
@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
@Rahuλ G, it's very interesting. Is really because of keyboard?
Freewind
@Freewind, As he himself clarified in the discussion, Odersky uses a US keyboard. So this Swiss keyboard theory is obviously wrong. :)
missingfaktor
@Rahuλ, yes :) So, the true reason is a secret
Freewind
+3  A: 

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