views:

106

answers:

4

In scala, "here docs" is begin and end in 3 "

val str = """Hi,everyone"""

But what if the string contains the """? How to output Hi,"""everyone?

+2  A: 

you can't

scala heredocs are raw strings and don't use any escape codes if you need tripple quotes in a string use string-concatenation add them

Nikolaus Gradwohl
There are no escape characters? He couldn't do `/"/"/"`?
wheaties
no, not in a heredoc stringadding \ or / before the " would add \" or /" to the stringbut you can escape " in a normal string
Nikolaus Gradwohl
+2  A: 

You can't using the triple quotes, as far as I know. In the spec, section 1.3.5, states:

A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The sequence of characters is arbitrary, except that it may contain three or more consuctive quote characters only at the very end. Characters must not necessarily be printable; newlines or other control characters are also permitted. Unicode escapes work as everywhere else, but none of the escape sequences in (§1.3.6) is interpreted.

So if you want to output three quotes in a string, you can still use the single quote string with escaping:


scala> val s = "Hi, \"\"\"everyone"
s: java.lang.String = Hi, """everyone
Arjan Blokzijl
You could also use the unicode escape sequence.
jhominal
So, there is no way to do this in heredoc. I don't understand why scala not support it.
Freewind
@jhominal: that still won't work if you unicode the three quote characters within a multi line string. It will still be interpreted as the end of the multi-line string literal
Arjan Blokzijl
+4  A: 

Since unicode escaping via \u0022 in multi-line string literals won’t help you, because they would be evaluated as the very same three quotes, your only chance is to concatenate like so:

"""Hi, """+"""""""""+"""everyone"""

The good thing is, that the scala compiler is smart enough to fix this and thus it will make one single string out of it when compiling.

At least, that’s what scala -print says.

object o {
  val s = """Hi, """+"""""""""+"""everyone"""
  val t = "Hi, \"\"\"everyone"
}

and using scala -print

Main$$anon$1$o.this.s = "Hi, """everyone";
Main$$anon$1$o.this.t = "Hi, """everyone";

Note however, that you can’t input it that way. The format which scala -print outputs seems to be for internal usage only.

Still, there might be some easier, more straightforward way of doing this.

Debilski
+5  A: 

It's a totally hack that I posted on a similar question, but it works here too: use Scala's XML structures as an intermediate format.

val str = <a>Hi,"""everyone</a> text

This will give you a string with three double quotation marks.

pr1001
@pr1001, this is very useful, thank you
Freewind
Sure thing. I have to say, I'm rather pleased with it. ;-)
pr1001