字符串插值转义引用PITA

时间:2013-10-22 12:10:31

标签: scala string-interpolation

令我疯狂的是,字符串插值有一些特殊的规则,不允许从a + b样式直接翻译:

// ok
def test(f: java.io.File) = {
  val abs = f.getAbsoluteFile
  val isF = abs.isFile
  "select " + (if (isF) "file" else "folder") +"\"" + abs.getName +"\" of folder"
}

// fail
def test(f: java.io.File) = {
  val abs = f.getAbsoluteFile
  val isF = abs.isFile
  s"select ${if (isF) "file" else "folder"} \"${abs.getName}\" of folder"
}

然后有一个可爱的错误信息:

<console>:38: error: value $ is not a member of String
         s"select ${if (isF) "file" else "folder"} \"${abs.getName}\" of folder of the front window"
                                                     ^

这里的s-string有什么问题?

1 个答案:

答案 0 :(得分:17)

问题在于,您不能将未转义的引号保留在单引号字符串中,就像在文字和文件夹中添加引号一样。尝试使用三引号字符串,它允许在其中使用未转义的引号(它仅以引号的第二个三元组终止):

s"""select ${if (isF) "file" else "folder"} "${abs.getName}" of folder"""