Scala Newbie alert:
basically I’m trying to do something like this: where I pattern match and return a String.
scala> def processList(list: List[String], m: String): String={list foreach (x=> m match{
| case "test" => "we got test"
| case "test1"=> "we got test1"})}
:10: error: type mismatch;
found : Unit
required: String
def processList(list: List[String], m: String): String={list foreach (x=> m match{
I know I can set a var and return it after the for comp… but that doesn’t seem to be the Scala way.
It is not completely clear to me what exactly it is that you are trying to do. Do you just want to test whether a certain element is present in the list? Or do you want to return a list of strings with some transformation? The latter, for example, can be written like so:
And for the former you could write something like:
In any case: the foreach method on a List loops over every element in a list, applying the given function to each element. It is mainly used for side-effecting, such as printing something to the console, or writing to a file. The function passed to the foreach method,must return the Unit type, which is like void in Java. You cannot return a single String from it, therefore.