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

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

-- [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:

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:

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" }