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 Answers1

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
}