How to create typed list in scala 3 macro using reflection API

How to create following code in scala 3 macro using reflection API:

import scala.quoted.*
def m(using Quotes) =
  import quotes.reflect.*
  val b = '{
    val value: List[String] = List.apply("AAAAAA")
  }
  println(b.asTerm.show(using Printer.TreeAnsiCode))
  b

I tried:

import scala.quoted.*
def m(using Quotes) =
  import quotes.reflect.*
  val ss = Symbol.newVal(Symbol.spliceOwner, "value",
    AppliedType(TypeRepr.of[List], List(TypeRepr.of[String])),
        Flags.EmptyFlags, Symbol.noSymbol)
  val v = Apply(TypeApply(Select.unique(
    Ident(Symbol.requiredModule("scala.collection.immutable.List").termRef), "apply"),
    List(TypeTree.of[String])), List('{"AAAAA"}.asTerm))
  val sv = ValDef(ss, Some(v))
  val b = Block(List(sv), Ident(ss.termRef))
  println(b.show(using Printer.TreeStructure))
  b.asExpr

Got the following error:

-- [E007] Type Mismatch Error: -------------------------------------------------
1 |r
  |^
  |Found:    List[String]
  |Required: List[String]
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  |
  | Tree: scala.collection.immutable.List.apply[String](["AAAAA" : String]*)
  | I tried to show that
  |   List[String]
  | conforms to
  |   List[String]
  | but the comparison trace ended with `false`:
  |
  |   ==> List[String]  <:  List[String]
  |   <== List[String]  <:  List[String] = false
  |
  | The tests were made under the empty constraint
   -----------------------------------------------------------------------------
1 error found

Any ideas would be welcome.

1 Like

Try making it inline or transparent inline. Mark the return type List[String] and Any respectively.

Also, the function does not seem to have the standard macro structure - an inline function that has a splice call that returns an Expr. See the logged example in Scala 3 Macros | Macros in Scala 3 | Scala Documentation.

HTHs