在Scala中转义底线以实现Java互操作性 [英] Escaping underscore for Java interoperability in Scala
问题描述
假设我有一些Scala代码,该代码调用一个Java库,该库使用 _
作为标识符(而且,我确实这样做了-这是很长的故事).这是一个简化的示例:
Suppose I've got some Scala code that calls a Java library that uses _
as an identifier (and I do—it's a long story). Here's a simplified example:
public class StupidUnderscore {
public static String _() { return "Please give me a real name!"; }
}
没问题,对吧?逃脱吧:
No problem, right? Just escape it:
scala> StupidUnderscore.`_`
res0: String = Please give me a real name!
这一直有效,直到今天早上我试图更新到Scala 2.10.2:
And this has always worked, until I tried to update to Scala 2.10.2 this morning:
scala> StupidUnderscore.`_`
<console>:1: error: wildcard invalid as backquoted identifier
StupidUnderscore.`_`
^
这是由于更改导致的,该更改显示在2.10.1中并修复了
This is due to a change that showed up in 2.10.1 and fixes this issue. From the commit message:
禁止
_
作为标识符,它只会带来不良后果.
Prohibit
_
as an identifier, it can only bring badness.
当然,但是我不知道为什么这意味着我无法摆脱它-我认为这就是反引号的用途.
Well, sure, but I don't know why that means I can't escape it—I thought that's what backquotes were for.
我是否必须编写Java包装程序才能使其正常工作?还有其他方法可以在Scala中引用Java库的 _
方法吗?
Am I going to have to write a Java wrapper to get this to work? Is there some other way I can refer to a Java library's _
method in Scala?
作为一个脚注,我已经确认无需编写任何新的Java就可以解决此问题:
As a footnote, I've confirmed that it's possible to work around this issue without writing any new Java:
object AwfulMacroHack {
import scala.language.experimental.macros
import scala.reflect.macros.Context
def _impl(c: Context) = {
import c.universe._
c.Expr[String](
Select(Ident(newTermName("StupidUnderscore")), newTermName("_"))
)
}
def `I'm not named _!` = macro _impl
}
然后:
scala> AwfulMacroHack.`I'm not named _!`
res0: String = Please give me a real name!
不过,我不确定这是否比Java帮助程序解决方案更可怕.
I'm not sure this is any less horrible than the Java helper solution, though.
推荐答案
Since backticks are the mechanism for Java interop on identifiers (e.g. Thread.yield()
), I doubt there's another way without using Reflection. I'd say your best bet (until the bug is fixed) is to write a static helper method in Java to access the _
.
我知道这是完全荒谬的,但它可能仍然比使用反射更好.他们使用该补丁破坏了Java互操作性,因此最终将不得不解决这个问题.但是,直到他们这样做为止,我认为它还是坏了.
I know this is totally ridiculous, but it's probably still better than using reflection. They broke Java interop with that patch, so they'll have to address this issue eventually. Until they do, however, I think it's just broken.
这篇关于在Scala中转义底线以实现Java互操作性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!