使用Java代码中的Scala类型别名 [英] Using Scala type aliases from Java code
问题描述
假设我在scala中定义了类型别名
Suppose I have type alias defined in scala as
object Foo {
type Bar = Option[String]
}
看起来我不能像那样在Java代码中引用别名(它只是抱怨找不到符号):
It looks like I cannot refer to alias in Java code like that (it simply complains cannot find symbol):
import Foo.*;
public class Cafebabe {
void bar(Bar x) {
//...
}
}
我也尝试过静态导入。
(更多具体来说,我有java反射代码,我无法更改,需要知道参数类型,我需要将Bar别名提供给它。)
我知道,我可以在Scala中创建包装器
I know, I can create wrapper in Scala
class BarWrapper(value: Bar)
但也许我错过了其他方式?
but maybe I'm missing some other way?
推荐答案
类型别名仅对Scala编译器可见,并且与泛型类型一样,它们不会出现在JVM类文件中的任何位置。
Type aliases are only visible to the Scala compiler, and like generic types they don't appear anywhere in the JVM class files.
如果您使用的是Java,那么由于 javac 无法知道类型别名 Bar <,因此使用非混淆类型
Option [String]
卡住了您在Scala代码中声明的/ code>。无论你在哪里使用 Bar
只需使用 Option [String]
(这是 scala.Option< ;字符串>
在Java中)它应该可以正常工作。
If you're in Java, you're stuck using the unaliased type Option[String]
since javac has no way of knowing about the type alias Bar
that you declared in your Scala code. Wherever you would have used Bar
just use Option[String]
(which is scala.Option<String>
in Java) and it should work fine.
这篇关于使用Java代码中的Scala类型别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!