Cannot compile code from documentation example

I cannot compile this metaprogramming example:

import scala.quoted.*

// make available the necessary compiler for runtime code generation
given staging.Compiler = staging.Compiler.make(getClass.getClassLoader)

val f: Array[Int] => Int = staging.run {
  val stagedSum: Expr[Array[Int] => Int] =
    '{ (arr: Array[Int]) => ${sum('arr)}}
  println(stagedSum.show) // Prints "(arr: Array[Int]) => { var sum = 0; ... }"
  stagedSum
}

f.apply(Array(1, 2, 3)) // Returns 6

I get two errors:

  1. no implicit argument of type scala.quoted.Quotes was found '{ (arr: Array[Int]) => ${sum('arr)}}
  2. value show is not a member of quoted.Expr[Array[Int] => Int] println(stagedSum.show) // Prints "(arr: Array[Int]) => { var sum = 0; ... }"

I am using the following settings:

    scalaVersion := "3.1.1",
    libraryDependencies += "org.scala-lang" %% "scala3-staging" % scalaVersion.value,

I was able to get it to compile and run after some substantial modifications:

import scala.quoted.*

// make available the necessary compiler for runtime code generation
given staging.Compiler = staging.Compiler.make(getClass.getClassLoader.nn)

val f: Array[Int] => Int = staging.run {
  val stagedSum: Expr[Array[Int] => Int] = '{ (arr: Array[Int]) => arr.sum } // '
  println(stagedSum.show) 
  stagedSum
}

@main def main(): Unit = {
  println(f(Array(1, 2, 3)))
}

Is the original code simply wrong? Or am I missing something?

Scala 3 documentation is still very much “work in progress” so there are many mistakes. Whenever you find a mistake, you can help improve! Contributing to the Docs | Scala 3 Documentation | Scala Documentation

2 Likes

I don’t think staging has had many users yet. I think its authors would appreciate a pull request with a fix or even just an issue reporting the problem.

1 Like