scala - Scala 2.10中的__FUNC__宏

标签 scala scala-2.10

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

最佳答案

import scala.reflect.macros.Context
import scala.language.experimental.macros

def impl(c: Context) = {
  import c.universe._
  c.enclosingMethod match {
    case DefDef(_, name, _, _, _, _) =>
      c.universe.reify(println(c.literal(name.toString).splice))
    case _ => c.abort(c.enclosingPosition, "no enclosing method")
  }
}

scala> def printEnclosingMethod = macro impl
defined term macro printEnclosingMethod: Unit

scala> def foo = printEnclosingMethod
foo: Unit

scala> foo
foo

scala> printEnclosingMethod
<console>:32: error: no enclosing method
              printEnclosingMethod
              ^

关于scala - Scala 2.10中的__FUNC__宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14114700/

相关文章:

Scala:为什么Actors 是轻量级的?

Scala 相当于 Haskell 的 where 子句?

scala - 为什么 Scala 的类型系统不是 Clojure 中的库

调用 copy() 时父特性的 Scala Case 类复制成员

intellij-idea - 在Controller中使用路由时IntelliJ IDEA报告突出显示错误

scala - 如何使用 Slick Lifted Embedding 更新多列?

关于 Heroku 问题的 Scala-redis 客户端连接到 RedisCloud

java - 如何使用反射从scala调用spark UDF?

scala - 为什么 2.10 坚持指定类型参数边界(在 2.9 中工作正常)?

scala - 了解 Scala -> 语法