Scalameta Decl.Def does not work in attribute definition method

I am using Scalameta annotation (v1.8.0) for def declaration:

trait MyTrait {
  @MyDeclDef
  def f2(): Int
}

      

The annotation class has only defined the return input, since this is:

import scala.meta._

class MyDeclDef extends scala.annotation.StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case defn: Decl.Def =>
        defn
      case _ =>
        println(defn.structure)
        abort("@MyDeclDef most annotate a Decl.Def")
    }
  }
}

      

a compiler error occurs:

Error:'=' expected but eof found.
def f2(): Unit
Error:illegal start of simple expression
def f2(): Unit

      

Also, if I use Decl.Var

to var v2: Int

it works great.

How to properly comment on a trait def

? Thanks to

+3


source to share


1 answer


I have not worked with scala-meta

before and have tried your example. It looks like we need to implement this method in macros. For example, if we provide a default implementation:

class MyDeclDef extends scala.annotation.StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case defn: Decl.Def =>
        val q"def $name(): $tpe" = defn
        q"def $name(): $tpe = 1"

      

we can instantiate MyTrait

and print the value of the method f2

:)



val x = new MyTrait
println(x.f2) // Prints 1

      

var v2: Int

works great because it fits case _

where we abort

are compiling.

0


source







All Articles