I'm getting a strange error with the following code.

I have a class Example, with a companion object, in which I have defined a string, SIGN. In class Example I have a method there I create a regular expression, and I use string interpolation so that I can use SIGN to build my regular expression.

This compiles, but I get a strange error at runtime. Is this a Scala bug? I'm using Scala 2.10.3 (on Windows 7).

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Example {
  import Example._
  def regex = s"""$SIGN?\d+""".r
}

object Example {
  private val SIGN = """(\+|-)"""
}


// Exiting paste mode, now interpreting.

defined class Example
defined module Example

scala> val e = new Example
e: Example = Example@77c957d9

scala> e.regex
scala.StringContext$InvalidEscapeException: invalid escape character at index 1 in "?\d+"
        at scala.StringContext$.treatEscapes(StringContext.scala:229)
        at scala.StringContext$$anonfun$s$1.apply(StringContext.scala:90)
        at scala.StringContext$$anonfun$s$1.apply(StringContext.scala:90)
        at scala.StringContext.standardInterpolator(StringContext.scala:123)
        at scala.StringContext.s(StringContext.scala:90)
        at Example.regex(<console>:9)
有帮助吗?

解决方案

After looking at the stack trace carefully, I see what's happening.

You can see that the method s is executed on the string, which handles the replacement of $SIGN. That method encounters the \d in the string and apparently tries to translate this; see the call to treatEscapes in the stack trace. The treatEscapes method doesn't recognize \d and throws an exception.

It can be fixed by writing \\d in the string, but that defeats the whole purpose of having a triple-quoted string...

Conclusion: It seems like string interpolation and triple-quoted strings interfere with each other. I'd say this is a Scala bug. (Why does the s method treat escapes?).

edit - This indeed looks like bug SI-6476 as Travis Brown pointed out in a comment.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top