I’m learning Scala as it fits my needs well but I am finding it hard to structure code elegantly. I’m in a situation where I have a List x and want to create two Lists: one containing all the elements of SomeClass and one containing all the elements that aren’t of SomeClass.
val a = x collect {case y:SomeClass => y}
val b = x filterNot {_.isInstanceOf[SomeClass]}
Right now my code looks like that. However, it’s not very efficient as it iterates x twice and the code somehow seems a bit hackish. Is there a better (more elegant) way of doing things?
It can be assumed that SomeClass has no subclasses.
EDITED
While using plain
partitionis possible, it loses the type information retained bycollectin the question.One could define a variant of the
partitionmethod that accepts a function returning a value of one of two types usingEither:Then the types are retained:
Of course the solution could be improved using builders and all the improved collection stuff 🙂 .
For completeness my old answer using plain
partition:For example: