Using Scala Type Aliases from Java Code

Suppose I have a type alias defined in scala as

object Foo { type Bar = Option[String] } 

It looks like I can't reference an alias in Java code like this (it just complains that it cannot find the character):

 import Foo.*; public class Cafebabe { void bar(Bar x) { //... } } 

I also tried static imports.

(More specifically, I have a java reflection code that I cannot change that needs to know the type of the parameter, and I need to pass it the alias Bar).

I know I can create a wrapper in Scala

 class BarWrapper(value: Bar) 

but maybe I missed some other way?

+8
java scala scala-java-interop type-alias
source share
1 answer

Alias ​​types are visible only to the Scala compiler, and, like generic types, they are not displayed anywhere in JVM class files.

If you are in Java, you are stuck using the unaliased type Option[String] , since javac is not aware of the Bar type alias you specified in the Scala code. Wherever you use Bar , just use Option[String] (which is scala.Option<String> in Java) and it should work fine.

+13
source share

All Articles