Is it possible to use one call to collect to make 2 new lists? If not, how can I do this using partition?
Is it possible to use one call to collect to make 2 new lists?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
collect(defined on TraversableLike and available in all subclasses) works with a collection and aPartialFunction. It also just so happens that a bunch of case clauses defined inside braces are a partial function (See section 8.5 of the Scala Language Specification [warning – PDF])As in exception handling:
It’s a handy way to define a function that will only accept some values of a given type.
Consider using it on a list of mixed values:
The argument to to
collectmethod is aPartialFunction[Any,String].PartialFunctionbecause it’s not defined for all possible inputs of typeAny(that being the type of theList) andStringbecause that’s what all the clauses return.If you tried to use
mapinstead ofcollect, the the double value at the end ofmixedListwould cause aMatchError. Usingcollectjust discards this, as well as any other value for which the PartialFunction is not defined.One possible use would be to apply different logic to elements of the list:
Although this is just an example, using mutable variables like this is considered by many to be a war crime – So please don’t do it!
A much better solution is to use collect twice:
Or if you know for certain that the list only contains two types of values, you can use
partition, which splits a collections into values depending on whether or not they match some predicate:The catch here is that both
stringsandintsare of typeList[Any], though you can easily coerce them back to something more typesafe (perhaps by usingcollect…)If you already have a type-safe collection and want to split on some other property of the elements, then things are a bit easier for you:
Hope that sums up how the two methods can help you out here!