Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala type aliases from Java code

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?

like image 755
om-nom-nom Avatar asked Dec 02 '12 21:12

om-nom-nom


People also ask

What is type alias in Scala?

A type alias is usually used to simplify declaration for complex types, such as parameterized types or function types. Let's explore examples of those aliases and also look at some illegal implementations of type aliases.

Does Java have type alias?

In Java, Alias is used when reference, which is of more than one, is linked to the same object. The issue with aliasing is when a user writes to a particular object, and the owner for the several other references do not expect that object to change.

How does Scala determine types when they are not specified?

Non-value types capture properties of identifiers that are not values. For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type.

How do you find the type of a variable in Scala?

Use the getClass Method in Scala The getClass method in Scala is used to get the class of the Scala object. We can use this method to get the type of a variable.


1 Answers

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.

like image 62
DaoWen Avatar answered Oct 08 '22 03:10

DaoWen