Printing a Val with ${...}, Surrounded by Parentheses?

739 views
Skip to first unread message

Kevin Meredith

unread,
Sep 8, 2015, 10:08:35 AM9/8/15
to scala-user
Given the following `val`:

scala> val x = 100

x: Int = 100



The following works:


scala> println(s" ${x} ")

 100


But, the following fails:


scala> println(s"\" ${x} \" ")

<console>:12: error: value $ is not a member of String

       println(s"\" ${x} \" ")

                    ^

<console>:12: error: value \ is not a member of Int

       println(s"\" ${x} \" ")

                         ^


How can I fix this?


Rex Kerr

unread,
Sep 8, 2015, 10:16:39 AM9/8/15
to Kevin Meredith, scala-user
Use triple quotes: s""""$x"""".  Or define a double quote character: val q = '"', and then use it: s"$q$x$q".  Escaping doesn't work "normally" in interpolated strings.

  --Rex

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Kevin Wright

unread,
Sep 8, 2015, 10:22:30 AM9/8/15
to Rex Kerr, Kevin Meredith, scala-user
That said... there's a proposal to support a $" notation as part of this SIP: https://github.com/scala/scala/pull/4663

Feel free to vote for it in the scala/slip bitter channel!

Jasper-M

unread,
Sep 8, 2015, 10:23:03 AM9/8/15
to scala-user, kevin.m....@gmail.com
Then how does escaping work in interpolated strings? Because apparently it does know what escaping is:

scala> s"\"
scala.StringContext$InvalidEscapeException: invalid escape character at index 0 in "\"
    ...
scala> s"\\"
res1: String = \

Can you escape anything other than the escape character?

Best,
Jasper

Op dinsdag 8 september 2015 16:16:39 UTC+2 schreef Rex Kerr:

Rex Kerr

unread,
Sep 8, 2015, 10:26:05 AM9/8/15
to Jasper-M, scala-user, Kevin Meredith
The interpolated string parses the escape at runtime (or not, in the case of raw"\\\").  So it's not very helpful for determining compile-time string boundaries.

 --Rex

Seth Tisue

unread,
Sep 8, 2015, 12:01:47 PM9/8/15
to scala-user
This is something of an FAQ. It's https://issues.scala-lang.org/browse/SI-6476
Reply all
Reply to author
Forward
0 new messages