0

I'm new to scala and I'm trying to learn it. I'm stuck with an very simple thing which I cannot figure out. I simply want, inside a for loop, to check if the current item is present in a map then use that value, otherwise calculate it with a function. It should be preatty easy but coming from python I cannot understand where the mistake is.

      val predictions = for (review <- testValuesAsList;
                             if (storage.contains("review")){prediction = mymap("review")}
                               else {prediction = computeItemAvgRat(review._2, trainValuesAsList)}
                             ) yield (review._3, prediction)
      return predictions

1 Answer 1

1

There are no for loops in Scala, only for comprehensions; they are just sugar syntax for map, flatMap and withFilter calls.
And that is what is making your code fail.

IMHO, the for syntax is rarely better than just calling the combinators explicitly.

val predictions = testValuesAsList.map {
  case (_, b, c) => // I don't know what would be proper names for the variables.
    val prediction = myMap.getOrElse(
      key = "review",
      default = computeItemAvgRat(b, trainValuesAsList)
    )

    c -> prediction
}
Sign up to request clarification or add additional context in comments.

1 Comment

ok got it! thanks!

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.