score:59
This is a bug in Scala:
but maybe you can use:
scala> import org.apache.commons.lang.StringEscapeUtils.escapeJava
import org.apache.commons.lang.StringEscapeUtils.escapeJava
scala> escapeJava("this is a string\nover two lines")
res1: java.lang.String = this is a string\nover two lines
score:0
Taking @Pascalius suggestion a few steps further. class StringImprovements extends and inherits AnyVal.
object StringUtil{
implicit class StringImprovements(val s: String) extends AnyVal {
def dqt = "\""+s+"\"" // double quote
def sqt = s"'$s'" // single quote
}
}
Scala only uses the StringImprovements class to create an intermediate object on which to call implicitly the two extension methods dqt & sqt. Nevertheless, we can eliminate the creation of this object and improve performance by making the class inherit from AnyVal. For Scala provides the value type specifically for such cases where the compiler will replace the object by just making the call to the method directly.
Here is a simple example using the above implicit class in an intermix where we use named variables (string & boolean) and a function in the interpolation string.
import StringUtil._
abstract class Animal {
...
override def toString(): String = s"Animal:${getFullName().dqt}, CanFly:$canFly, Sound:${getSound.dqt}"
}
score:2
It's heavily used in my case, therefore I created this version:
object StringUtil{
implicit class StringImprovements(s: String) {
def quoted = "\""+s+"\""
}
}
val myStatement = s"INSERT INTO ${tableName.quoted} ..."
score:3
How about
s"This is ${"\"" + variable + "\""}" inserted in string with quotes
score:3
Starting Scala 2.13.6 escaped double quotes work as expected in string interpolations
Welcome to Scala 2.13.6 (OpenJDK 64-Bit Server VM, Java 15.0.2).
Type in expressions for evaluation. Or try :help.
scala> s"\"Hello\""
val res0: String = "Hello"
scala> s"$"Hello$""
val res1: String = "Hello"
score:5
As already mentioned, this is a known bug in Scala. A workaround is to use \042
.
score:5
Simple way:-
val str="abc"
println(s"$str") //without double quotes
println(s"""\"$str\"""") // with double quotes
score:8
For your use case, they make it easy to achieve nice syntax.
scala> implicit class `string quoter`(val sc: StringContext) {
| def q(args: Any*): String = "\"" + sc.s(args: _*) + "\""
| }
defined class string$u0020quoter
scala> q"hello,${" "*8}world"
res0: String = "hello, world"
scala> "hello, world"
res1: String = hello, world // REPL doesn't add the quotes, sanity check
scala> " hello, world "
res2: String = " hello, world " // unless the string is untrimmed
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:
scala> val `"` = "\""
": String = "
scala> s"${`"`}"
res3: String = "
scala> s"hello, so-called $`"`world$`"`"
res4: String = hello, so-called "world"
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:
scala> f"%qhello, world%q"
<console>:9: error: conversions must follow a splice; use %% for literal %, %n for newline
That's worth an enhancement request.
Update: just noticed that octals aren't deprecated in interpolations yet:
scala> s"\42hello, world\42"
res12: String = "hello, world"
score:9
This fixed the problem for me, I tested this out and this is what I used.
raw"""
Inside this block you can put "as many" quotes as you "want" and even "${5 + 7}" interpolate inside the quotes
"""
http://docs.scala-lang.org/overviews/core/string-interpolation.html#the-raw-interpolator
score:10
An example:
scala> val username="admin"
> username: String = admin
scala> val pass="xyz"
> pass: String = xyz
scala> println(s"""{"username":"$username", "pass":"$pass"}""")
> {"username":"admin", "pass":"xyz"}
score:26
Another solution (also mentioned in the Scala tracker) is to use
case _ => s"${'"'}$value${'"'}"
Still ugly, but sometimes perhaps may be preferred over triple quotes.
It seems an escape sequence $"
was suggested as a part of SIP-24 for 2.12:
case _ => s"$"$value$""
This SIP was never accepted, as it contained other more controversial suggestions. Currently there is an effort to get escape sequence $"
implemented in 2.13 as Pre SIP/mini SIP $” escapes in interpolations.
score:46
You don't need to escape quotes in triple-quoted string, so s""""$value"""""
will work. Admittedly, it doesn't look good either.
Source: stackoverflow.com
Related Query
- How to insert double quotes into String with interpolation in scala
- How to load a json file which is having double quotes within a string into a dataframe in spark scala
- Scala String interpolation with Format, how to change locale?
- How do I format a string with string interpolation in Scala as a fixed width string?
- How do I convert a Scala Double into a binary 64-bit String
- How to split a string with double quotes " as the delimiter?
- How to replace double quotes with space in Scala
- How to do string interpolation in scala with more than 22 arguments
- How to replace double quotes with a newline character in spark scala
- How to insert dynamically developed string query in to with column function scala
- How to remove double quotes and extra delimiter(s) with in double quotes of TextQualifier file in Scala
- How to transform a string column of a dataframe into a column of Array[String] with Apache Spark and Scala
- What's the difference between raw string interpolation and triple quotes in scala
- How to find if a Scala String is parseable as a Double or not?
- String interpolation in Scala 2.10 - How to interpolate a String variable?
- How to load 100 million records into MongoDB with Scala for performance testing?
- How to substitute an empty string (or null) with a default string concisely in Scala
- String interpolation with triple quotes and multiple lines
- How to know if a Scala file modified with IntelliJ Idea is saved and if it is checked into CVS?
- Scala Regex with $ and String Interpolation
- Scala : Way to use a function directly into the println(...) using string interpolation
- Scala string interpolation with escaped quote fails
- Is this a bug in Scala 2.10 String Interpolation inside a multiline String with backslash?
- How to use DataFrame.explode with a custom UDF to split a string into substrings?
- Scala - Spark - How to transform a dataframe containing one string column to a DF with columns with the rigth type?
- how to decode Java strings with Unicode escapes etc. from Scala JavaTokenParsers into unescaped strings?
- Insert data into a Hive table with HiveContext using Spark Scala
- Scala String Interpolation with Underscore
- Scala how to escape 3 double quotes
- How to validate string format with scala in compile time
More Query from same tag
- Schema design for topics with ratings
- intellij idea scala formatting
- Use list of integers as argument for fill function
- How to trigger tests related to a particular file on Scala SBT
- Spark Dataframes , WithColumn
- Adding new task dependencies to built-in SBT tasks?
- Writing to Rabbitmq with Scala
- Brainfuck compiler in scala
- Scala constructor, logic and inheritance
- Scala: "Parameter type in structural refinement may not refer to an abstract type defined outside that refinement"
- HadoopRDD error while trying to count lines in a file hosted on local HDFS using spark shell
- Merge two first and second elements in ArrayBuffer
- Why does Scala construct a new Tuple when unpacking a Tuple?
- groupBy on multiple values
- Index of word in string 'covering' certain position
- Type erasure leads to missing parameter type for expanded function
- How to check if some type confirms to generic type bounds in Scala macros?
- Difference between case class with parentheses and without
- Too many elements when initialize hashmap
- Debugging with Gatling - println if status is 500
- How to make virtual time pass in a test in Cats Effect 3?
- Unable to execute scala code on Azure DataBricks cluster
- scala infix function with additional parameters
- Slick SourceCodeGenerator From SQL File
- getting null Graph fields from spark map operation after collect
- scala uanpply without parameter
- Howto create a .jar including both sources (.java and .scala) and classes with sbt?
- Getting unary error for escaped characters in Scala
- Stable Scala 2.8 plugin
- Underscores in numeric literals in scala