Behavior of groupBy().mapValues() differs in Scala 2.12 vs Scala 2.13

Hi,

I observed a difference in behavior with the following piece of code in Scala 2.12 vs Scala 2.13:

object Solution {
  def groupAnagrams(strs: Array[String]): List[List[String]] = {
    val groups = strs.groupBy(str => str.groupBy(identity).mapValues(_.length))
    groups.map(_._2.toList).toList
  }

  def main(args: Array[String]): Unit = {
    println(groupAnagrams(Array("eat","tea","tan","ate","nat","bat")))
  }
}

Here the creation of groups use a Map as the key, this produces the following output in Scala 2.12.15:

List(List(eat, tea, ate), List(tan, nat), List(bat))

and the following output in Scala 2.13.7:

List(List(ate), List(tea), List(eat), List(bat), List(nat), List(tan))

I assume this is due to the MapView that is returned by the mapValues function.
Just wanted to confirm if this behavior is expected.

Thanks,
Krishna Rajendram Bashyam.

Note that mapValues is deprecated in 2.13.

When I compile your code, the deprecation warning tells me:

warning: method mapValues in trait MapOps is deprecated (since 2.13.0): Use .view.mapValues(f). A future version will include a strict version of this method (for now, .view.mapValues(f).toMap).

2 Likes

It’s a pity that this was not changed in Scala 3. Since moving from Scala 2.13 to 3.0 is some work after all, this would have not added much. (There are a few more of these cases, if i remember correctly). In Scala 3.1.3 i still get this warning.

To aid migration, Scala 3.0 uses 2.13’s standard library unaltered. Eventually we’ll be free to start changing it again.

2 Likes

3 Likes