使用 Scala 2.10.0-RC1,我尝试在 Windows 文件路径中使用字符串插值,例如:
val path = s"""c:\foo\bar\$fileName.csv"""
并得到了一个例外
java.lang.StringIndexOutOfBoundsException: String index out of range: 11
没有多行字符串文字 ( """
) 它工作得很好 val path = s"""c:\foo\bar\$fileName.csv""" val path = s"c:\foo\bar\${fileName}.csv " //> 路径:字符串 = c:\foo\bar\myFile.csv
进一步测试以重现该问题:
object wcScala10 {
util.Properties.versionString //> res0: String = version 2.10.0-RC1
val name = "James" //> name : String = James
val test1 = s"Hello $name" //> test1 : String = Hello James
val test2 = s"""Hello $name""" //> test2 : String = Hello James
val test3 = """Hello \$name""" //> test3 : String = Hello \$name
val test4 = s"""Hello \$name""" //> java.lang.StringIndexOutOfBoundsException:
//> String index out of range: 7
}
这个异常是由于错误吗?还是我在进行字符串插值时根本不允许在 $ 符号之前使用反斜杠?
这是更多的堆栈跟踪:
java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.charAt(String.java:686)
at scala.collection.immutable.StringOps$.apply$extension(StringOps.scala :39)
at scala.StringContext$.treatEscapes(StringContext.scala:202)
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:120)
at scala.StringContext.s(StringContext.scala:90)
at wcScala10$$anonfun$main$1.apply$mcV$sp(wcScala10.scala:9)
at org.scalaide.worksheet.runtime.library.WorksheetSupport$$anonfun$$exe
cute$1.apply$mcV$sp(WorksheetSupport.scala:76)
at org.scalaide.worksheet.runtime.library.WorksheetSupport$.redirected(W
orksheetSupport.scala:65)
at org.scalaide.worksheet.runtime.library.WorksheetSupport$.$execute(Wor
ksheetSupport.scala:75)
at wcScala10$.main(wcScal
Output exceeds cutoff limit.
更新:
现在标记为 Scala 2.10.1-RC1 已修复
https://issues.scala-lang.org/browse/SI-6631
顺便说一句,即使在修复之后,进行插值和避免转义的正确方法是使用raw
:
val path = raw"c:\foo\bar\$fileName.csv"
例如
val fileName = "myFileName" //> fileName : String = myFileName
val path = raw"c:\foo\bar\$fileName.csv" //> path : String = c:\foo\bar\myFileName.csv