Having trouble escaping all the quotes in my function
(basic usage of it -> if i find a string do nothing, if its not a string add " in the begin and end)
code snippet :
def putTheDoubleQuotes(value: Any): Any = {
value match {
case s: String => s //do something ...
case _ => s"\"$value\"" //not working
}
}
only thing that worked was :
case _ => s"""\"$value\""""
is there a better syntax for this ?
it looks terrible and the IDE (IntelliJ) marks it in red (but lets you run it which really pisses me!!!!!)
You don't need to escape quotes in triple-quoted string, so
s""""$value"""""
will work. Admittedly, it doesn't look good either.For your use case, they make it easy to achieve nice syntax.
Squirrel the implicit away in a package object somewhere.
You can name the interpolator something besides
q
, of course.Last week, someone asked on the ML for the ability to use backquoted identifiers. Right now you can do res3 but not res4:
Another idea that just occurred to me was that the f-interpolator already does some work to massage your string. For instance, it has to handle "%n" intelligently. It could, at the same time, handle an additional escape "%q" which it would not pass through to the underlying formatter.
That would look like:
That's worth an enhancement request.
Update: just noticed that octals aren't deprecated in interpolations yet:
This is a bug in Scala:
but maybe you can use:
An example:
scala> val username="admin"
scala> val pass="xyz"
scala> println(s"""{"username":"$username", "pass":"$pass"}""")
As already mentioned, this is a known bug in Scala. A workaround is to use
\042
.