Scala and tail recursion

There are various stack overflow answers that explain the conditions under which tail recursion in Scala is possible . I understand the limitations and how and where I can use tail recursion. The part that I don't understand is the reason for limiting private or final methods.

I have not investigated how the Scala compiler actually converts a recursive function into a non-recursive one at the bytecode level, but suppose it does something like the following. I have a class Foowith a recursive function mod:

class Foo {
  def mod(value: Int, denom: Int): Int = {
    if(denom <= 0 || value <= 0) 0
    else if(0 <= value && value < denom) value
    else mod(value - denom, denom)
  }
}

With the basic modular function that I present, the Scala compiler translates something like a pseudo-Java-Scala like:

class Foo {
  def mod(value: Int, denom: Int): Int = {
    if(denom <= 0 || value <= 0) return 0
    while(value > denom) value -= denom
    return value
  }
}

(I can believe I messed up this translation, but I don't think the details are important.)

, , Foo:

class Bar extends Foo {
  def mod(value:Int, denom: Int): Int = 1
}

, ? JVM Foo/Bar mod, mod, . , ?

, , :

  • - Scala ( , . , ?)

  • in Foo mod mod-non-recursive, Foo mod .

+3
2

, . , Foo JAR.

Jar Foo :

class Bar extends Foo {
  def mod(value:Int, denom: Int): Int = {
    Logger.log("Received mod with "+value+" % "+denom)
    super.mod(value, denom)
}

, Foo mod , Bar, Foo, ( ) mod Bar, Foo's.

, , .

, , , , .

private, , - , , .

+6

. , Foo , ( , , .)

-1

Source: https://habr.com/ru/post/1722355/


All Articles