E153: summonFrom에 잘못된 패턴을 썼어요

E153: summonFrom에 잘못된 패턴을 썼어요 (Unexpected Pattern For SummonFrom)

summonFromcase 절에서 잘못된 패턴과 함께 사용할 때 발생하는 에러예요. summonFrom 매크로는 타입 패턴(x: T)이나 와일드카드 패턴(_)만 받아들여요.

출처: Scala 3 Reference

본문

summonFrom은 컴파일 타임에 implicit 값을 소환(summon)하려는 구조예요. 그래서 임의의 값 패턴이 아니라, implicit이 존재하는지 확인하는 패턴을 요구해요.

Example

import scala.compiletime.summonFrom

inline def example = summonFrom {
  case 42 => "found"
}

Error

-- [E153] Syntax Error: example.scala:4:7 --------------------------------------
4 |  case 42 => "found"
  |       ^^
  |       Unexpected pattern for summonFrom. Expected `x: T` or `_`
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The pattern "42" provided in the case expression of the summonFrom,
  |  needs to be of the form `x: T` or `_`.
  |
  |  Example usage:
  |  inline def a = summonFrom {
  |   case x: T => ???
  |  }
  |
  |  or
  |  inline def a = summonFrom {
  |   case _ => ???
  |  }
   -----------------------------------------------------------------------------

Solution

import scala.compiletime.summonFrom

// Use typed pattern to check for implicit presence
inline def example = summonFrom {
  case given String => "found a String"
  case _ => "not found"
}
import scala.compiletime.summonFrom

// Use binding with type pattern
inline def example2 = summonFrom {
  case s: String => s"found: $s"
  case _ => "not found"
}

더 알아보기

  • summonFrom과 컴파일 타임 프로그래밍에 대한 자세한 내용은 Scala 3 Reference의 inline 문서를 참고하세요.