Solved: Scala 3 inline: why does an assignment prevent inline reduction

I got the following function from the tutorial and changed it slightly:

  inline def power(x: Double, inline n: Int): Double =
    inline if (n == 0) 
      then
        1.0
      else inline if (n % 2 == 1) 
        then
          x * power(x, n - 1)
          // val next = n - 1 
          // x * power(x, next)
        else 
          power(x * x, n / 2)

As shown above, the code compiles and executes. However, if I replace the x * power(x, n - 1) with the commented lines, I get the error listed below.

Isn’t the assignment equivalent? Both use the same subtraction operation.

TIA

[error] 122 |    power(2,2)
[error]     |    ^^^^^^^^^^
[error]     |Cannot reduce `inline if` because its condition is not a constant value: next.==(0)
[error]     |---------------------------------------------------------------------------
[error]     |Inline stack trace
[error]     |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[error]     |This location contains code that was inlined from Data4.scala:96
[error]  96 |    inline if (n == 0) 
[error]     |    ^
[error]  97 |      then
[error]  98 |        1.0
[error]  99 |      else inline if (n % 2 == 1) 
[error] 100 |        then
[error] 101 |          //x * power(x, n - 1)
[error] 102 |          val next = n - 1 
[error] 103 |          x * power(x, next)
[error] 104 |        else 
[error] 105 |          power(x * x, n / 2)
[error]     |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[error]     |This location contains code that was inlined from Data4.scala:96
[error] 103 |          x * power(x, next)
[error]     |              ^^^^^^^^^^^^^^
[error]     |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[error]     |This location contains code that was inlined from Data4.scala:96
[error] 105 |          power(x * x, n / 2)
[error]     |          ^^^^^^^^^^^^^^^^^^^
[error]      ---------------------------------------------------------------------------
[error] one error found

The val has to be inline

1 Like

@BalmungSan Thank you.