可以将抽象类或特征上的宏应用于所有子类吗?

说我在一个库中具有某些特征(或抽象类)Foo,该库通常由用户代码扩展并且需要某种方法numArgs

trait Foo {
  // Number of arguments to the default constructor
  def numArgs: Int
}

现在numArgs编写起来很简单,但是我想生成它是令人讨厌的样板。我可以通过反射来做到这一点,但是它很丑陋,并且无法移植到其他后端,例如ScalaJS,ScalaNative或GraalVM。

是否可以编写仅可以将 应用于Foo的宏注释(要求在Foo的每个子类上使用)这样才能生成该方法?

wangke1836 回答:可以将抽象类或特征上的宏应用于所有子类吗?

不。抽象类(或特征)上的宏注释只能更改此类(特征)及其伴随对象的AST。您不能更改父母,子女,兄弟姐妹等。这样做是为了使宏注释在这种意义上是本地的。

此外,如果特征不是密封的,则甚至在编译时也不知道其子类。

如果将类(特征)和子类嵌套到某个对象中,则可以注释该对象。

如果要修改任意树,则可能需要通过Scalameta进行编译器插件或代码生成(源代码的生成)。

我想在您的用例中,您可以将宏注释替换为def宏

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

def numArgs[A]: Int = macro impl[A]

def impl[A: c.WeakTypeTag](c: blackbox.Context): c.Tree = {
  import c.universe._
  val numArgs = weakTypeOf[A].typeSymbol.asClass.primaryConstructor.asMethod.paramLists.flatten.length
  q"$numArgs"
}

class A(i: Int,s: String)

numArgs[A] // 2

或Shapeless(如果子类是案例类)

import shapeless.ops.hlist.Length
import shapeless.ops.nat.ToInt
import shapeless.{::,Generic,HList,HNil,Nat}

def numArgs[A] = new PartiallyApplied[A]

class PartiallyApplied[A] {
  def apply[L <: HList,N <: Nat]()(implicit gen: Generic.Aux[A,L],length: Length.Aux[L,N],toInt: ToInt[N]): Int = toInt()
}

case class A(i: Int,s: String)

numArgs[A]() // 2
本文链接:https://www.f2er.com/3121595.html

大家都在问