Andrei Iatsuk
Andrei Iatsuk

Reputation: 468

Why Scala can't inferred type of method without parentheses and dots

I wrote simple code, that returns immutable map of characters and their indexes as vector:

def indexes(string: String): Map[Char, Vector[Int]] = (0 until string.length).
  foldLeft(Map[Char, Vector[Int]]()){
    (m, i) => m + (string(i) -> m.getOrElse(string(i), Vector()).:+(i))
  }

For example:

println(indexes("Mississippi"))
// Map(M -> Vector(0), i -> Vector(1, 4, 7, 10), s -> Vector(2, 3, 5, 6), p -> Vector(8, 9))

Why Scala can't inferred that m.getOrElse(string(i), Vector()) :+ i is Vector[Int] and compile it? I should wrote m.getOrElse(string(i), Vector()).:+(i) instead.

Upvotes: 0

Views: 64

Answers (1)

Leo C
Leo C

Reputation: 22439

It'll work fine with the Map value parenthesized:

def indexes(string: String): Map[Char, Vector[Int]] = (0 until string.length).
  foldLeft(Map[Char, Vector[Int]]()){
    (m, i) => m + (string(i) -> (m.getOrElse(string(i), Vector()) :+ i))
  }

indexes("Mississippi")
// res1: Map[Char,Vector[Int]] = Map(M -> Vector(0), i -> Vector(1, 4, 7, 10), s -> Vector(2, 3, 5, 6), p -> Vector(8, 9))

Without parenthesizing the Map value, the (k -> a :+ b) key-value portion of the code below will be treated as (k -> a) :+ b, hence causes compilation error:

    (m, i) => m + (string(i) -> m.getOrElse(string(i), Vector()) :+ i)

// <console>:28: error: value :+ is not a member of (Char, Vector[Int])

Upvotes: 1

Related Questions