简体   繁体   English

捕获按名称呼叫参数的表示形式

[英]Capture the representation of a call-by-name argument

I'm trying to print the call-by-name argument passed to a function, that is: 我正在尝试打印传递给函数的按名称调用参数,即:

def testme(arg: => Int) println(arg)

And call it like so: 并这样称呼它:

test(sum(List(1, 2, 3))

Provided that sum method exists. 只要存在sum方法。 I want testme to print sum(List(1, 2, 3)) and not the sum itself. 我希望testme打印sum(List(1, 2, 3))而不是sum本身。

Is there a way to achieve this? 有没有办法做到这一点?

No, it's not possible without hacking the compiler. 不,没有破解编译器是不可能的。 When you're passed f: => A, calling f evaluates it immediately. 当您通过f:=> A时,调用f立即对其进行求值。 It isn't ever in an intermediate form of the type you would like, because scala is compiled down to java byte code, not interpreted like a scripting language. 它永远不会以您想要的类型的中间形式出现,因为scala被编译为Java字节代码,而不像脚本语言那样被解释。

Edit: As Regis points out, hacking the compiler is easier than in some languages because scala exposes an api to the compiler, via scala macros. 编辑:正如Regis指出的那样,对黑客进行编译比在某些语言中容易,因为scala通过scala宏向编译器公开了api。 It is still fairly complicated, and you are probably better off figuring out your solution another way. 它仍然相当复杂,您最好以另一种方式来解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM