9

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 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Type aliases have to appear somewhere in JVM class files, otherwise you wouldn't be able to use aliases from other libraries. But as far as I found they are scrambled in some "additional data" field in class definition.
@Keros - That's a good point, but by the same logic generic type signature information are also included in class files in some format. Whatever format they use when they compile type declarations, it's sadly not something that Java recognizes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.