2016-02-11 225 views
0

的的toString如何编写宏注释这看起来像使用和@named("+2") _ + 2产生:宏注释覆盖斯卡拉功能

new (Int => Int) { 
    override def toString(): String = "+2" 
    def apply(x: Int): Int = x + 2 
} 
+0

适用于什么类型的对象的宏? –

+0

Function1(带参数的函数) –

回答

1

您可以创建宏返回一个匿名函数。你没有完全理解你想要的语法,好像@在方法内部不起作用。

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) 
    } 
}