Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation escape quote PITA

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?

like image 738
0__ Avatar asked Oct 22 '13 12:10

0__


1 Answers

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"""
like image 161
Shadowlands Avatar answered Oct 18 '22 15:10

Shadowlands