简体   繁体   English

使用Java代码中的Scala类型别名

[英]Using Scala type aliases from Java code

Suppose I have type alias defined in scala as 假设我在scala中定义了类型别名

object Foo {
  type Bar = Option[String]
}

It looks like I cannot refer to alias in Java code like that (it simply complains cannot find symbol ): 看起来我不能像Java那样在Java代码中引用别名(它只是抱怨无法找到符号 ):

import Foo.*;

public class Cafebabe {
  void bar(Bar x) {
  //...
  }
}

I've tried static import as well. 我也尝试过静态导入。

(More specifically, I have java reflection code which I cannot change that needs to know parameter type and I need to feed Bar alias to it). (更具体地说,我有java反射代码,我无法更改,需要知道参数类型,我需要将Bar别名提供给它)。

I know, I can create wrapper in Scala 我知道,我可以在Scala中创建包装器

class BarWrapper(value: Bar)

but maybe I'm missing some other way? 但也许我错过了其他一些方式?

Type aliases are only visible to the Scala compiler, and like generic types they don't appear anywhere in the JVM class files. 类型别名仅对Scala编译器可见,并且与泛型类型一样,它们不会出现在JVM类文件中的任何位置。

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. 如果您使用的是Java,那么您将使用非混淆类型的Option[String]因为javac无法知道您在Scala代码中声明的类型别名Bar Wherever you would have used Bar just use Option[String] (which is scala.Option<String> in Java) and it should work fine. 无论你在哪里使用Bar只需使用Option[String] (Java中的scala.Option<String> ),它应该可以正常工作。

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

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