Scala错误SI-7914是否有任何解决方法-从Scala宏返回apply方法?

问题描述:

在我们的库中,我们定义了一个宏,如下所示:

In our library we have a macro defined like so:

def extractNamed[A]: Any = macro NamedExtractSyntax.extractNamedImpl[A]

此宏使用其类型签名返回一个apply方法,该方法的参数与键入其的案例类的apply方法相匹配.

This macro uses its type signature to return an apply method whose arguments match the apply method of the case class on which it is typed.

想法是,这允许我们库的用户使用Scala的命名参数,如下所示:

The idea is that this allows the user of our library to make use of Scala's named parameters like so:

lazy val fruitExtractor = extractNamed[Fruit](
  name = FruitTable.name,
  juiciness = FruitTable.juiciness
)

但是,这似乎不起作用-而是在编译时返回error: Any does not take parameters.

However, this doesn't seem to work - it instead returns error: Any does not take parameters at compile-time.

这似乎是由 SI-7914 ,因为它可以在用户明确调用应用时起作用,即:

It seems like this is caused by SI-7914 because it does work if the user explicitly calls apply, i.e.:

lazy val fruitExtractor = extractNamed[Fruit].apply(
  name = FruitTable.name,
  juiciness = FruitTable.juiciness
)

我们可以通过简单地将返回的方法重命名为明智的方法来解决此问题,但是还有其他方法可以解决此问题而无需显式的方法调用?

We can work around this by simply renaming the returned method to something sensible, but is there any other way to work around this without requiring an explicit method call?

如何从宏返回Dynamic的子类?然后,您可以定义applyDynamicapplyDynamicNamed来执行所需的操作.为了提高编译时的安全性,您还可以将那些xxxDynamic方法也设置为宏.我刚刚检查了一下,它完全符合您想要的语法.

How about returning an subclass of Dynamic from a macro? Then you could define applyDynamic and applyDynamicNamed to do what you want. For additional compile-time safety, you can have those xxxDynamic methods be macros as well. I just checked and this works exactly with the syntax that you want to have.