1

I have repetitive blocks of code I want to copy, like old C-style macros. I'm trying quasiquotes:

import scala.language.experimental.macros

object CodeBlock {
  val quasi = q"""def foo() = {"bar"}"""
}

case class A() {
// ??? want quasi here
}

case class B() {
// ??? want quasi here
}
1
  • You cannot. Macro can generate body of member, but not introduce new member in existing type: class Foo { def bar = macro myMacroGenBody } Commented Dec 3, 2019 at 17:06

1 Answer 1

1

Try macro annotation

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.whitebox

@compileTimeOnly("enable macro paradise")
class codeBlock extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro CodeBlockMacro.impl
}

object CodeBlockMacro {
  def impl(c: whitebox.Context)(annottees: c.Tree*): c.Tree = {
    import c.universe._
    annottees match {
      case q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" :: tail =>
        q"""
          $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self =>
            def foo() = {"bar"}
            ..$stats
          }

          ..$tail
        """
    }
  }
}

@codeBlock
case class A()

@codeBlock
case class B()

//Warning:scalac: {
//  case class A extends scala.Product with scala.Serializable {
//    def <init>() = {
//      super.<init>();
//      ()
//    };
//    def foo() = "bar"
//  };
//  ()
//}
//Warning:scalac: {
//  case class B extends scala.Product with scala.Serializable {
//    def <init>() = {
//      super.<init>();
//      ()
//    };
//    def foo() = "bar"
//  };
//  ()
//}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.