Scala raw strings error in unicode escape
Asked Answered
G

1

6

In a Scala String need to include this literal verbatim: \usepackage{x}. Thus, desired would be that for

val s = """ ... \usepackage{X} ... """

println(s)
... \usepackage{X} ...

Attempts so far include,

scala> """\usepackage{X}"""
<console>:1: error: error in unicode escape
       """\usepackage{X}"""
            ^

scala> raw"""\usepackage{X}"""
<console>:1: error: error in unicode escape
       raw"""\usepackage{X}"""
               ^

Single double-quoted strings prove unsuccessful as well.

Following http://docs.scala-lang.org/overviews/core/string-interpolation.html , a working example includes

scala> raw"a\nb"
res1: String = a\nb

which does not cover unicode cases.

Gennygeno answered 5/6, 2014 at 11:5 Comment(1)
If you have an answer, do not edit your original question, post an answer and accept it.Shrubbery
S
10

You appear to be facing issue SI-4706: Unicode literal syntax thwarts common use cases for triple-quotes.

In Scala, unicode escape sequences are processed not only inside character or string literals. It may not be obvious that the following code would work:

scala> 5 \u002B 10
res0: Int = 15

Unfortunately, there doesn't seem to be a good way around this if you don't want to disable unicode escapes completely (-Xno-uescape, only available until Scala 2.13.1, see PR #8282 and ee8c1ef8).

One of workarounds suggested in the SI-4706 issue is separating the backslash character:

scala> """\""" + """usepackage{X}"""
res1: String = \usepackage{X}
Sylvestersylvia answered 5/6, 2014 at 11:48 Comment(3)
Thanks for the '-Xno-uescape' tip. \u even in comments causes compilations to fail.Bowing
You can also Unicode-encode both the backslash and the 'u': """\u005c\u0075""" correctly gives \u.Lustick
@Lustick I'm three years late to the party, but that deserves a standalone answerJeffersonjeffery

© 2022 - 2024 — McMap. All rights reserved.