E202: Quoted Type Missing

E202: Quoted Type Missing

이 에러는 따옴표로 감싼 표현('{ ... }) 안에서 타입 파라미터를 참조하는데, 해당하는 Type[T] 인스턴스가 스코프에 없을 때 발생해요.

출처: Scala 3 Reference

본문

Scala는 런타임에 타입 소거(erasure)를 사용하기 때문에 실행 중에는 타입 정보가 사라져요. 매크로와 따옴표(quotes)를 쓸 때는 컴파일러가 scala.quoted.Type[T] 인스턴스를 이용해 타입 정보를 따옴표로 감싼 코드 안으로 전달해 줘야 해요.

예시 (Example)

import scala.quoted.{Expr, Quotes}

case class Thing[T]()

def foo[T](using Quotes): Expr[Thing[T]] = '{ Thing[T]() }

에러 (Error)

-- [E202] Staging Issue Error: example.scala:5:52 ------------------------------
5 |def foo[T](using Quotes): Expr[Thing[T]] = '{ Thing[T]() }
  |                                                    ^
  |Reference to T within quotes requires a given scala.quoted.Type[T] in scope
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Referencing `T` inside a quoted expression requires a `scala.quoted.Type[T]` to be in scope.
  | Since Scala is subject to erasure at runtime, the type information will be missing during the execution of the code.
  | `scala.quoted.Type[T]` is therefore needed to carry `T`'s type information into the quoted code.
  | Without an implicit `scala.quoted.Type[T]`, the type `T` cannot be properly referenced within the expression.
  | To resolve this, ensure that a `scala.quoted.Type[T]` is available, either through a context-bound or explicitly.
   -----------------------------------------------------------------------------

설명 (Explanation)

따옴표로 감싼 표현 안에서 T를 참조하려면 scala.quoted.Type[T]가 스코프에 있어야 해요. Scala는 런타임에 소거되기 때문에 코드 실행 중에는 타입 정보가 사라져요. 그래서 T의 타입 정보를 따옴표 안의 코드로 전달하려면 scala.quoted.Type[T]가 필요한 거예요. 암시적 scala.quoted.Type[T]가 없으면 표현 안에서 타입 T를 제대로 참조할 수 없어요. 이 문제를 해결하려면 컨텍스트 바운드 또는 명시적인 방법으로 scala.quoted.Type[T]를 제공해 주세요.

해결 방법 (Solution)

타입 정보를 사용할 수 있도록 컨텍스트 바운드 T: Type을 추가해요.

import scala.quoted.{Expr, Quotes, Type}

case class Thing[T]()

def foo[T: Type](using Quotes): Expr[Thing[T]] = '{ Thing[T]() }

대안으로, Type[T]using 파라미터로 명시적으로 제공할 수도 있어요.

import scala.quoted.{Expr, Quotes, Type}

case class Thing[T]()

def bar[T](using Quotes, Type[T]): Expr[Thing[T]] = '{ Thing[T]() }