小编Eri*_*her的帖子

Scala 2.10中的__FUNC__宏

在Scala 2.9.x中,我编写了func函数,它返回了函数的名称,其中func()的执行方式与FUNC C预处理器宏类似.据我所知,在Scala2.10中,我应该能够写一些比抛出异常更优雅的东西来完成这项工作.

我该怎么做?在此先感谢您的帮助.

object TestMyLog extends App {
    val MatchFunc = """(.+)\(.+""".r

def func(i_level: Int): String = {
    val s_rien = "functionNotFound"
    try {
    throw new Exception()
    } catch {
    case unknwn => unknwn.getStackTrace.toList.apply(i_level).toString match {
            case MatchFunc(funcs) => funcs.split('.').toList.last
        case _ => s_rien
    }
    } finally {
    s_rien      
    }
}

def tracedFunction1 = func(1)
def tracedFunction2 = func(1)

println(tracedFunction1)
assert(tracedFunction1=="tracedFunction1")
println(tracedFunction2)
assert(tracedFunction2=="tracedFunction2")
}
Run Code Online (Sandbox Code Playgroud)

scala scala-2.10

9
推荐指数
2
解决办法
474
查看次数

如何使用scala宏打印变量名称和值?

我敢肯定,有一种更优雅的方式来编写以下宏,该宏将打印变量的名称和值:

def mprintx(c: Context)(linecode: c.Expr[Any]): c.Expr[Unit] = {
    import c.universe._

    val namez = (c.enclosingImpl match {
        case ClassDef(mods, name, tparams, impl) =>
            c.universe.reify(c.literal(name.toString).splice)
        case ModuleDef(mods, name, impl) =>
            c.universe.reify(c.literal(name.toString).splice)
        case _ => c.abort(c.enclosingPosition, "NoEnclosingClass")
    }).toString match {
        case r_name(n) => n
        case _         => "Unknown?"
    }

    val msg = linecode.tree.productIterator.toList.last.toString.replaceAll("scala.*\\]", "").replaceAll(namez+"\\.this\\.", "").replaceAll("List", "")
    reify(myPrintDln(c.Expr[String](Literal(Constant(msg))).splice+" ---> "+linecode.splice))
}

def myPrintIt(linecode: Any) = macro mprintx
Run Code Online (Sandbox Code Playgroud)

由以下程序调用:

object Zabi2 extends App {
val l = "zab"
val kol = 345
var zub = …
Run Code Online (Sandbox Code Playgroud)

scala-macros

6
推荐指数
1
解决办法
684
查看次数

得到电话课

我想得到一个宏的调用类,但我的代码不起作用:

def __CLASS__(c: Context) = {
    import c.universe._
    c.enclosingClass match {
    case ClassDef(mods, name, tparams, impl) =>
    c.universe.reify(println(
            "\n  mods "+c.literal(mods.toString).splice
            +"\n  name "+c.literal(name.toString).splice
            +"\n  tparams "+c.literal(tparams.toString).splice
            +"\n  impl "+c.literal(impl.toString).splice
            ))
    case _ => c.abort(c.enclosingPosition, "NoEnclosingClass")
    }
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助.

scala scala-2.10 scala-macros

4
推荐指数
1
解决办法
719
查看次数

标签 统计

scala ×2

scala-2.10 ×2

scala-macros ×2