0
的的toString如何編寫宏註釋這看起來像使用和@named("+2") _ + 2
產生:宏註釋覆蓋斯卡拉功能
new (Int => Int) {
override def toString(): String = "+2"
def apply(x: Int): Int = x + 2
}
的的toString如何編寫宏註釋這看起來像使用和@named("+2") _ + 2
產生:宏註釋覆蓋斯卡拉功能
new (Int => Int) {
override def toString(): String = "+2"
def apply(x: Int): Int = x + 2
}
您可以創建宏返回一個匿名函數。你沒有完全理解你想要的語法,好像@在方法內部不起作用。
import scala.language.experimental.macros
import scala.reflect.macros._
object Named {
def build[T, R](name: String)(applyFunc: T => R): T => R = macro Named.impl[T, R]
def impl[T: c.WeakTypeTag, R: c.WeakTypeTag](c: whitebox.Context)(name: c.Expr[String])(applyFunc: c.Expr[T => R]): c.Expr[T => R] = {
import c.universe._
val functionType = weakTypeOf[T]
val resultType = weakTypeOf[R]
c.Expr[T => R](
c.typecheck(q"""
new ($functionType => $resultType) {
override def toString() = $name
def apply(x: $functionType): $resultType = $applyFunc(x)
}
"""))
}
}
,然後用這個宏生成自己的功能:
class NamedTest {
@Test
def testNamed() = {
val b = Named.build[Int, Int]("+2")(_ + 2)
assertEquals(4, b(2))
assertEquals("+2", b.toString)
}
}
適用於什麼類型的對象的宏? –
Function1(帶參數的函數) –