noncom
noncom

Reputation: 4992

Scala - foldLeft type inference fail

In my code, I have the following:

  type Occurrences = List[(Char, Int)]

  def subtract(x: Occurrences, y: Occurrences): Occurrences = {
    val yMap = y.toMap
    x foldLeft (List[(Char, Int)]()) {  // ERROR
        case (a: List[(Char, Int)], xe: (Char, Int)) =>
        if(yMap.contains(xe._1)) (xe._1 -> (xe._2 - yMap(xe._1))) :: a
        else a
    }
  }

It fails on compile-time, at the { that is right before the error mark in the code. The error message is the following:

missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: Int

1) How could that be? As far as I can see, there is no room for misinterpretation of type information here, and I find a lot of such examples over the internet. How can I fix that?

2) Why is it thinking that the expected type is Int after all?

Upvotes: 3

Views: 1985

Answers (1)

kiritsuku
kiritsuku

Reputation: 53348

The error occurs because you wrote xs foldLeft (init) (f) instead of (xs foldLeft init)(f) or xs.foldLeft(init)(f).

The former does not work, because Scalas operator notation rules allow only to leave the dot and parentheses if a call occurs in form obj method param, which is not the case with foldLeft because it has two parameter lists.

Upvotes: 8

Related Questions