It drives me crazy that string interpolation has some special rules that disallow a straight forward translation from a + b style:

// 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"
}

And then with a lovely error message:

<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"
                                                     ^

What is wrong with the s-string here?

有帮助吗?

解决方案

The problem is that you can't leave unescaped quotes in a single-quoted string, as you do when you put quotes around the words file and folder. Try it with a triple-quoted string, which allows unescaped quotes within it (it is only terminated by a second triple of quotes):

s"""select ${if (isF) "file" else "folder"} "${abs.getName}" of folder"""
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top