Scala is a polymorphic function for filtering the input list.

Finding a more elegant solution

I have this piece of code, I just use it in test cases where there is no need to handle errors. What does he do:

  • enter a list of lines
  • Analyze them using the DSJSonmapper.parseDSResult method.
  • filters them and extracts the Right value from each of them (on the left is an exception)

The code is as follows:

def parseDs(ins: List[String]) = { def filterResults[U, T](in: List[Either[U, T]]): List[T] = { in.filter(y => y.isRight).map(z => z.right.get) } filterResults(ins.map(x => DSJsonMapper.parseDSResult(x))) } 

Now I have not done many polymorphic functions, but it works. However, it seems to me that this is a little ugly. Has anyone got the best offer on how to do the same.

I know that this will come down in case of personal preference. But suggestions are welcome.

+7
source share
2 answers

collect is executed for this situation:

 def filterMe[U,T](in: List[Either[U,T]]): List[T] = in.collect{ case Right(r) => r } 

In fact, it’s so good that you can skip def and just

 ins.map(DSJsonMapper.parseDsResult).collect{ case Right(r) => r } 
+11
source

Rex's answer is perhaps a little clearer, but here's a slightly shorter alternative that parses and filters in one step:

 ins.flatMap(DSJsonMapper.parseDSResult(_).right.toOption) 

Here we take the right projection of each analysis result and turn it into Option (which will be None if the parsing failed and Some(whatever) otherwise). Since we use flatMap , None not displayed as a result, and values ​​are pulled from Some s.

+7
source

All Articles