Scala Map.mapValues stackoverflowerror

前端 未结 1 2032
故里飘歌
故里飘歌 2020-12-31 22:23

The following code results in a StackOverflowError on the last line.

object StackTest extends App{
    @tailrec def incrementValues(acc: Map[String, Int], in         


        
相关标签:
1条回答
  • 2020-12-31 23:03

    mapValues is known to be a trap, as it indeed creates only a wrapping view function instead of eagerly producing a new collection. Therefore, in your example you create a data structure of nesting level 10,000.

    You can use the regular map method:

    acc.map(tup => (tup._1, tup._2 + 1))
    

    or

    acc.map { case (key, value) => (key, value + 1) }
    
    0 讨论(0)
提交回复
热议问题