Why am I getting "template type incompatible with expected type"?

I encountered an error in my Scala code that I cannot solve on my own (I am new to Scala). I have the following code:

def myFunction(list: List[Any]): String = { var strItems : String = ""; list.foreach(item => { strItems += item match { case x:JsonSerializable => x.toJson() case y:String => ("\"" + y + "\"") case _ => item.toString } if(item != list.last) strItems += ","; }) strItems; } 

The error I am getting is:

error: template type is incompatible with the expected type; found: String required: unit case y: String => ("\" "+ y +" \ "")

Any idea why?

PS: is there a more efficient way to encode myFunction

+4
source share
2 answers

In terms of the original question, the code does not compile because it requires parentheses around the match, i.e. strItems += (item match { ... })

A more “functional” way of writing this may be something like:

 def myFunction(list:List[Any]):String = { val strings:List[String] = list.map{ case x:JsonSerializable => x.toJson() case y:String => ("\"" + y + "\"") case z => z.toString } strings.mkString(",") } 

You could probably use the view to make it lazy and more “fulfilled,” although I don’t know from my head if this combines the two base mkString ( map and mkString ) into a single bypass.

+7
source

Here is a form of your code that compiles (without description for JsonSerializable ) (in Scala 2.8) along with a more concise wording (which also ends up without dots):

 object Javier01 { def javFunc(list: List[Any]): String = { val strItems = new StringBuilder() list.foreach { item => strItems.append ( item match { // case x: JsonSerializable => x.toJson() case y: String => "\"" + y + "\"" case _ => item.toString } ) if (item != list.last) strItems.append(",") } strItems.toString } def rrsFunc(anys: List[Any]): String = anys map { // case x: JsonSerializable => x.toJson() case s: String => "\"" + s + "\"" case x => x.toString } mkString "," def main(args: Array[String]): Unit = { val stuff = List(true, 1, 123.456, "boo!") printf(" stuff : %s%njavFunc(stuff): %s%nrrsFunc(stuff): %s%n%n", stuff, javFunc(stuff), rrsFunc(stuff)) } } 

Exiting this run:

 % scala Javier01 stuff : List(true, 1, 123.456, boo!) javFunc(stuff): true,1,123.456,"boo!" rrsFunc(stuff): true,1,123.456,"boo!" 
0
source

Source: https://habr.com/ru/post/1312923/


All Articles