如何在 Scala 中获取函数名称? [英] How do I get the function name in Scala?

查看:58
本文介绍了如何在 Scala 中获取函数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个简单的任务.只需显示整个表达式,如:

Consider a simple task. Just show the whole expression like:

    a operator b = c

在 Common Lisp 中,它可能是这样的:

In Common Lisp it might look like this:

    (defun applyOp (a b op) 
        (format t "~S ~S ~S = ~S" a op b (apply op (list a b))))

    $ (applyOp 1 2 #'logand)
    1 #<FUNCTION LOGAND> 2 = 0

在 Scala 中,这似乎不是那么简单:

In Scala it seems not so trivial:

    def applyOperator(x: Int, y: Int, op: (Int, Int) => Int) = { 
        println(x + s" $op " + y + " = " + op(x,y)) 
    }

    scala> applyOperator(1, 2, _ & _)
    1 <function2> 2 = 0 // how to get the function name? 

的名字是什么?

推荐答案

另一种功能齐全的方法是一个简单的 .

Another full-featured approach would be a simple macro.

假设您编写最简单的宏来提取表达式和类型名的字符串表示:

Suppose you write simplest macro extracting string representation of expression and typename:

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

class VerboseImpl(val c: Context) {
  import c.universe._

  def describe[T: c.WeakTypeTag](expr: c.Expr[T]): c.Expr[(String, String, T)] = {
    val repr = expr.tree.toString
    val typeName = weakTypeOf[T].toString
    c.Expr[(String, String, T)](q"($repr, $typeName, $expr)")
  }

}

object Verbose{
  def apply[T](expr: T): (String, String, T) = macro VerboseImpl.describe[T]
}

接下来在另一个源(最好在另一个子项目中)你可以写

Next in another source (preferrable in another subproject) you can write

val a = 2
val b = 3
println(Verbose(a + b + 3))

并查看魔术字符串

(a.+(b).+(3),Int,8)

从这一点上,您可以增强宏以显示有关方法、参数、类型等的任何信息...

From this point you can enhance you macro to display any information about methods, parameters, types, etc...

请注意,宏是在编译时评估的.所以 Verbose.apply 调用的开销就像用两个字符串常量创建元组一样,所以虽然它是唯一的无样板、可扩展的方法,但它绝对是性能最高的

Note that macro is evaluated at compile time. So overhead of Verbose.apply call is like creating tuple with two string constants, so while it's the only boilerplatless, extensible approach, it's the definitely most performant

这篇关于如何在 Scala 中获取函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆