posted 8 years ago
I'm writing some code to parse a CSV file where I simply want to throw away any records that don't have the right format. I'm using Scala Try() to wrap the extraction process for each line of input data, which produces a sequence of Try's. Then I filter these and do a get() on the Successes to create a list of my required class instances. But I'm wondering if there's a more idiomatic way of extracting the results from the sequence of Try's.
Here is a simplified version of my code, which reads Strings from an imaginary CSV file, and wants to convert them to a Fubar which has 3 Int fields. I know it's not the done thing, but in this case I'm not interested in trapping any parsing exceptions - I just want the valid data.
Now I can run this code with some dummy data:
Results from Step 1 are fine:
Now run the second step:
The end results are exactly what I want i.e. a sequence of valid instances of Fubar:
So my code does what I want and it's pretty concise, but I still think there is vague code-smell around the Try/Success processing. Anybody got any better ideas?
No more Blub for me, thank you, Vicar.