Using Scala type aliases from Java code

对着背影说爱祢 提交于 2019-11-28 07:21:30

问题


Suppose I have type alias defined in scala as

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):

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).

I know, I can create wrapper in Scala

class BarWrapper(value: Bar)

but maybe I'm missing some other way?


回答1:


Type aliases are only visible to the Scala compiler, and like generic types they don't appear anywhere in the JVM class files.

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.



来源:https://stackoverflow.com/questions/13673839/using-scala-type-aliases-from-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!