Back to Scala3

E219: Cannot Instantiate Quoted Type Variable

docs/_docs/reference/error-codes/E219.md

3.8.42.4 KB
Original Source

E219: Cannot Instantiate Quoted Type Variable

This error is emitted when a type variable in a quoted pattern is used after new, which is not allowed.

In quoted patterns (used in macros), lowercase type names are treated as type variables that match any type. However, type variables cannot be instantiated with new because the compiler cannot know at compile time which constructor to call.

If you meant to refer to an actual class, wrap the name in backticks to escape it. If you need to create instances in pattern matching, consider using the lower-level quotes.reflect API.


Example

scala
import scala.quoted.*

def inspectMacro(x: Expr[Any])(using Quotes): Expr[String] =
  x match
    case '{ new t($arg) } => '{ "found new with arg" }
    case _ => '{ "other" }

Error

scala
-- [E219] Staging Issue Error: example.scala:5:16 ------------------------------
5 |    case '{ new t($arg) } => '{ "found new with arg" }
  |                ^
  |Quoted pattern type variable `t` cannot be instantiated.
  |If you meant to refer to a class named `t`, wrap it in backticks.
  |If you meant to introduce a binding, this is not allowed after `new`. You might
  |want to use the lower-level `quotes.reflect` API instead.
  |Read more about type variables in quoted pattern in the Scala documentation:
  |https://docs.scala-lang.org/scala3/guides/macros/quotes.html#type-variables-in-quoted-patterns
  |

Solution

If you want to match a specific class, use backticks to escape the name:

scala
import scala.quoted.*

class myClass(val value: Int)

def inspectMacro(x: Expr[Any])(using Quotes): Expr[String] =
  x match
    case '{ new `myClass`($arg) } => '{ "found myClass" }
    case _ => '{ "other" }

For more complex pattern matching involving new, use the quotes.reflect API:

scala
import scala.quoted.*

def inspectMacro(x: Expr[Any])(using Quotes): Expr[String] =
  import quotes.reflect.*
  x.asTerm match
    case Apply(Select(New(tpt), _), args) => '{ "found new expression" }
    case _ => '{ "other" }
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>