关于scala宏的功能

时间:2014-12-25 11:07:33

标签: scala scala-macros

网上有关于scala宏的文档很少。 我想知道如何用scala宏实现它们。 由于它们只是样品,请不要问我想要它们的原因。 请将以下代码视为伪代码。

1种打印类型

def add[T1,T2](a:T1,b:T2) = {
  if (a.type == b.type) println(b.type.name)  // determinated at compiling time
  a+b
}

2为每种类型生成函数

val typelist = [ Int,Double ]
def mul5(x:T) = x*5
// I want to have mul5 for each type in the typelist. i.e.
def mul5(x:Int) = x*5
def mul5(x:Double) = x*5

3字面替换,如C中的宏

def hello(x) = for ( i <- x ) println(i) // a macro named hello
// use hello to substitute following code
hello(List(1,2,3,4)) // the generated code should be  for ( i <- List(1,2,3,4) ) println(i)
hello(List("123","123","xx","yy"))

0 个答案:

没有答案