title: tail rec kotlin list
body: <p>I'm trying to do some operations that would cause a StackOverflow in Kotlin just now.</p>
  
  <p>Knowing that, I remembered that Kotlin has support for <code>tailrec</code> functions, so I tried to do:</p>
  
  <pre><code>private tailrec fun Turn.debuffPhase(): List&lt;Turn&gt; {
      val turns = listOf(this)
      if (facts.debuff == 0 || knight.damage == 0) {
          return turns
      }
  
      // Recursively find all possible thresholds of debuffing
      return turns + debuff(debuffsForNextThreshold()).debuffPhase()
  }
  </code></pre>
  
  <p>Upon my surprise that IDEA didn't recognize it as a <code>tailrec</code>, I tried to unmake it a extension function and make it a normal function:</p>
  
  <pre><code>private tailrec fun debuffPhase(turn: Turn): List&lt;Turn&gt; {
      val turns = listOf(turn)
      if (turn.facts.debuff == 0 || turn.knight.damage == 0) {
          return turns
      }
  
      // Recursively find all possible thresholds of debuffing
      val newTurn = turn.debuff(turn.debuffsForNextThreshold())
      return turns + debuffPhase(newTurn)
  }
  </code></pre>
  
  <p>Even so it isn't accepted. The important isn't that the last function call is to the same function? I know that the <code>+</code> is a sign to the <code>List</code> <code>plus</code> function, but should it make a difference? All the examples I see on the internet for tail call for another languages allow those kind of <a href="https://stackoverflow.com/questions/33923/what-is-tail-recursion">actions</a>.</p>
  
  <p>I tried to do that with <code>Int</code> too, that seemed to be something more commonly used than addition to lists, but had the same result:</p>
  
  <pre><code>private tailrec fun discoverBuffsNeeded(dragon: RPGChar): Int {
      val buffedDragon = dragon.buff(buff)
      if (dragon.turnsToKill(initKnight) &lt; 1 + buffedDragon.turnsToKill(initKnight)) {
          return 0
      }
  
      return 1 + discoverBuffsNeeded(buffedDragon)
  }
  </code></pre>
  
  <p>Shouldn't all those implementations allow for tail call? I thought of some other ways to solve that(Like passing the list as a <code>MutableList</code> on the parameters too), but when possible I try to avoid sending collections to be changed inside the function and this seems a case that this should be possible.  </p>
  
  <p>PS: About the question program, I'm implementing a solution to this <a href="https://code.google.com/codejam/contest/5304486/dashboard#s=p2&amp;a=2" rel="nofollow noreferrer">problem</a>.</p>