0

This is my code:

val foo = "\\foo" var escaped = "" foo.foreach(c => { escaped += c match { case '_' => "\\_" case '\\' => "\\textbackslash{}" case '~' => "\\textasciitilde{}" case '^' => "\\textasciicircum{}" case '&' => "\\&" case '%' => "\\%" case '#' => "\\#" case '{' => "\\{" case '}' => "\\}" case ch => ch } }) 

IntelliJ tells me that Pattern type is incompatible with expected type, found: Char, required: Unit. Why does this happen? c is obviously a Char, not a Unit.

2 Answers 2

2

The problem is you are matching escaped + char to '_' etc. Do match inside () then concat with another variable.

val foo = "\\foo" var escaped = "" foo.foreach((char : Char) => { escaped = escaped + (char match { case '_' => "\\_" case '\\' => "\\textbackslash{}" case '~' => "\\textasciitilde{}" case '^' => "\\textasciicircum{}" case '&' => "\\&" case '%' => "\\%" case '#' => "\\#" case '{' => "\\{" case '}' => "\\}" case ch => ch }) }) println(escaped) //prints \textbackslash{}foo 
Sign up to request clarification or add additional context in comments.

Comments

2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.