0

In Scala:

scala> val xs = List(List(1, 3, 5), List(3, 4, 30))
xs: List[List[Int]] = List(List(1, 3, 5), List(3, 4, 30))

scala> xs flatMap {x => x + 1}
<console>:9: error: type mismatch;
 found   : Int(1)
 required: String
              xs flatMap {x => x + 1}

Why?

Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219

3 Answers3

2

The simplest solution is to flat your list before executing map:

xs.flatten.map { _ + 1 }

The reason for your error is that flatMap doesn't flatten the collection on which you execute it, it flattens the results returning by the function in its argument.

mutantacule
  • 6,913
  • 1
  • 25
  • 39
2

String in that error message is an unfortunately misleading inference.

The error the compiler ideally would have given you is

found   : Int => Int
required: Int => List[Int]
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
1

x in the flatMap is a List[Int] not an Int, two solutions come to mind:

scala> xs.flatMap(identity).map(_ + 1)
res2: List[Int] = List(2, 4, 6, 4, 5, 31)

scala> xs.flatMap(_.map(_ + 1))
res3: List[Int] = List(2, 4, 6, 4, 5, 31)
Ende Neu
  • 15,581
  • 5
  • 57
  • 68