0

I'm reading a .csv file that returns a list of String lists, recipiesList, in the following format:

List(List(Portuguese Green Soup, Portugal), List(Grilled Sardines, Portugal), List(Salted Cod with Cream, Portugal))

I have a class Recipe, which has been defined in the following manner:

case class Recipe(name: String, country: String)

Is there any immediate way that I can transform recipiesList into a list of type List[Recipe]? Such as with map or some sort of extractor?

2 Answers 2

6

You can transform elements of a List using the map method:

val input = List(List("Portuguese Green Soup", "Portugal"),
    List("Grilled Sardines", "Portugal"),
    List("Salted Cod with Cream", "Portugal"))

val output = input map { case List(name, country) => Recipe(name, country) }
Sign up to request clarification or add additional context in comments.

5 Comments

It's safer to use collect instead of map when the given function is partial. That way, if your data is corrupt (say some element in input as three elements for some reason), it will simply be ignored, rather than throwing a MatchError.
@CyrilleCorpet, if my team start writing code that silently ignores errors in the input, I'll be having words! Better to use a case _ and do something with the errors
@TheArchetypalPaul, I'd rather silently ignore them than let them break my production app. My main point was that map with a partial function is not pure, it introduces (probably) unexpected errors, and should be avoided, when possible.
@CyrilleCorpet " I'd rather silently ignore them than let them break my production app" False dichotomy. You don't have to ignore them to avoid breaking the app
@TheArchetypalPaul I completely agree with you. But using map with only the expected case will break the app on unexpected cases. I like your idea with case _ which makes the function total, I just try to alert on the fact that you should not use a partial function where a total one is expected. In fact, if it where a sealed trait instead of List[String] as input type, the scala compiler itself would issue a warning.
3

The quick way would be:

recipiesList.map(s => Recipe(s(0), s(1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.