【发布时间】:2019-12-12 02:36:31
【问题描述】:
下面的代码会生成 OOM 错误,而我只附加到现有的 StringBuilder。请解释为什么会生成 OOM,因为我没有为每个递归创建任何新对象。
object BeerSong {
val song = StringBuilder.newBuilder
var count = 0
def recite(start : Int, end : Int): String = {
start match {
case 1 => song.append(s"$start bottles of beer on the wall, $start bottles of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n")
case 0 => song.append("No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.")
case _ => song.append(s"$start bottles of beer on the wall, $start bottles of beer.\nTake one down and pass it around, ${start.toInt - 1} bottles of beer on the wall.\n")
}
count += 1
if (count == end) {
song.toString()
}
recite(start -1, end)
}
【问题讨论】:
-
递归的
recite()方法没有出口。它没有办法终止。 -
请检查您的逻辑,就像您在比较
start和end值以终止递归逻辑一样。 -
你在哪里称呼这个
recite以及start和end的值是什么?
标签: scala out-of-memory