kavita kavita - 1 month ago 5x
Scala Question

foldLeft method in scala

I am using the following code to get a count of words in a text

.foldLeft(Map.empty[String, Float]){
(countsSource, wordSource) => countsSource + (wordSource -> (countsSource.getOrElse(wordSource, 0) + 1))}

I am getting an error that 1 should be a string. If i put it in quotes, it says that it should be a float.

What am I doing wrong?? Thanks for your help in advance


getOrElse's signature is as follows:

def getOrElse[B1 >: B](key: A, default: => B1): B1

Which means it doesn't necessarily return the type of the Map's value (B), but potentially a superclass B1. In your case, using the literal 0 doesn't inform the compiler that you're interested in a Float.

Using 0f instead would fix it:

l.foldLeft(Map.empty[String, Float]){
  (countsSource, wordSource) => countsSource + (wordSource -> (countsSource.getOrElse(wordSource, 0f) + 1))}