Well... the thing is that foreach on a collection type such as List[A] has following signature,
foreach(func: A => Unit): Unit
Which means that foreach wants a function of type A => Unit as parameter.
In this case, you have a String, and here foreach wants a function of type Char => Unit as parameter.
But look at the body of your function...
c => { escaped += c match { case '_' => ... ... } }
What you actually have here is,
c => { (escaped += c) match { case '_' => ... ... } }
And (escaped += c) is Unit. So to solve this all you have to use are proper parenthesis,
c => { escaped += (c match { case '_' => ... ... }) }
Also... you should avoid using this approach for building that string. You can just use a map to create your String instead of appending to it in a foreach
val foo = "\\foo" val escaped = foo.map(c => c match { case '_' => "\\_" case '\\' => "\\textbackslash{}" case '~' => "\\textasciitilde{}" case '^' => "\\textasciicircum{}" case '&' => "\\&" case '%' => "\\%" case '#' => "\\#" case '{' => "\\{" case '}' => "\\}" case ch => "" + ch }).mkString