scalainlinescala-3

How to write a inline for loop in scala3?


I have write some performance critical codes in scala, and encountered codes as following time by time:

var index = start - 1
while {index += 1; index < end} do something 

Then I want to write a inline version to avoid the var index and while { .. } again:

inline def forward(start: Int, end: Int)(inline body: Int => Unit): Unit =
    if start < end then
        body(start)
        forward(start + 1, end)(body)

I supposed that forward(start, end){ something } will generated almost the same code as the hand write while {}.

But I encountered a wired compile message confused me very much:

object InlineFor:
    val n: Int = 1

    inline def forward(start: Int, end: Int)(inline body: Int => Unit): Unit =
        if start < end then
            body(start)
            forward(start + 1, end)(body)

    def main(args: Array[String]): Unit =
        forward(0, 1)(println)  // This is OK
        forward(0, n)(println)  // This is failed

Maximal number of successive inlines (32) exceeded, Maybe this is caused by a recursive inline method? You can use -Xmax-inlines to change the limit.

Is there any thing wrong of the code? 3x very much.


Solution

  • The error message says it all: you have a inline recursive method.

    This is only supported with a known number of iterations (at compile time) and with a maximum number defined by a compiler flag -Xmax-inlines.

    There's no way the compiler can inline the code without knowing n in your code.

    Note that you don't need inline at all in your code, just annotate your method with @tailrec to enforce it is tail recursive and the compiler will generate optimized code.