添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

If we want to do compile-time pattern matching checks for string interpolation in Scala 2 we write:

implicit class StrInterp(sc : StringContext) {
  object si {
    def apply(args : Any*) : Any = macro siApplyMacro
    def unapply(arg : Any): Option[Seq[Any]] = macro siUnapplyMacro
val x = arg match {
  case si"my_pattern" => ???

In Scala 3 this is nontrivial:

  • Extension methods are limited to, well, methods, so an object cannot be placed as an extension.
  • Implicit classes cannot receive an inline StringContext.
  • The way to do it is:

    class SIParts[+P <: Tuple](parts : P): //P is a tuple representation of the SC parts
      transparent inline def apply(inline args: Any*): Any = ${siApplyMacro[P]('args, 'parts)}
      transparent inline def unapplySeq(inline arg: Any): Option[Seq[Any]] = ${siUnapplyMacro[P]('arg, `parts)}
    extension (inline sc : StringContext)
      transparent inline def si : SIParts[Tuple] = ${siPartsMacro('sc)}
    

    To me this seems highly burdensome and nontrivial.
    Is there a better way to do this currently?
    Is there a way to design the language better so this feature will be at least at par with Scala 2? E.g., allow extension fields (lazy vals and objects) and not just methods.

    To write a string interpolator with an apply and unapply. Both could be macros. old code In Scala 2 we would have written implicit...

    itype:enhancement area:metaprogramming