Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing Scala and Java: How to get generically typed constructor parameter right?

I have some legacy Java code that defines a generic payload variable somewhere outside of my control (i.e. I can not change its type):

// Java code
Wrapper<? extends SomeBaseType> payload = ...

I receive such a payload value as a method parameter in my code and want to pass it on to a Scala case class (to use as message with an actor system), but do not get the definitions right such that I do not get at least a compiler warning.

// still Java code
ScalaMessage msg = new ScalaMessage(payload);

This gives a compiler warning "Type safety: contructor... belongs to raw type..."

The Scala case class is defined as:

// Scala code
case class ScalaMessage[T <: SomeBaseType](payload: Wrapper[T]) 

How can I define the case class such that the code compiles cleanly? (sadly, changing the code of the Java Wrapper class or the type of the payload parameter is not an option)

Updated to clarify the origin of the payload parameter

Added For comparison, in Java I can define a parameter just in the same way as the payload variable is defined:

// Java code
void doSomethingWith(Wrapper<? extends SomeBaseType> payload) {}

and call it accordingly

// Java code
doSomethingWith(payload)

But I can't instantiate e.g. a Wrapper object directly without getting a "raw type" warning. Here, I need to use a static helper method:

static <T> Wrapper<T> of(T value) {
   return new Wrapper<T>(value);
}

and use this static helper to instantiate a Wrapper object:

// Java code
MyDerivedType value = ... // constructed elsewhere, actual type is not known!
Wrapper<? extends SomeBaseType> payload = Wrapper.of(value);

Solution

I can add a similar helper method to a Scala companion object:

// Scala code
object ScalaMessageHelper {
    def apply[T <: SomeBaseType](payload: Wrapper[T]) = 
        new ScalaMessage(payload)
}
object ScalaMessageHelper2 {
    def apply[T <: SomeBaseType](payload: Wrapper[T]) = 
        ScalaMessage(payload) // uses implicit apply() method of case class
}

and use this from Java to instantiate the ScalaMessage class w/o problems:

// Java code
ScalaMessage msg = ScalaMessageHelper.apply(payload);

Unless someone comes up with a more elegant solution, I will extract this as an answer...

Thank you!

like image 985
Erich Schreiner Avatar asked Jan 23 '13 13:01

Erich Schreiner


2 Answers

I think the problem is that in Java if you do the following:

ScalaMessage msg = new ScalaMessage(payload);

Then you are instantiating ScalaMessage using its raw type. Or in other words, you use ScalaMessage as a non generic type (when Java introduced generics, they kept the ability to treat a generic class as a non-generic one, mostly for backward compatibility).

You should simply specify the type parameters when instantiating ScalaMessage:

// (here T = MyDerivedType, where MyDerivedType must extend SomeBaseType
ScalaMessage<MyDerivedType> msg = new ScalaMessage<>(payload);

UPDATE: After seeing your comment, I actually tried it in a dummy project, and I actually get an error:

[error] C:\Code\sandbox\src\main\java\bla\Test.java:8: cannot find symbol
[error] symbol  : constructor ScalaMessage(bla.Wrapper<capture#64 of ? extends bla.SomeBaseType>)
[error] location: class test.ScalaMessage<bla.SomeBaseType>
[error]     ScalaMessage<SomeBaseType> msg = new ScalaMessage<SomeBaseType>(payload);

It seems like a mismatch between java generics (that we can emulate through exitsentials in scala ) and scala generics. You can fix this by just dropping the type parameter in ScalaMessage and using existentials instead:

case class ScalaMessage(payload: Wrapper[_ <: SomeBaseType]) 

and then instantiate it in java like this:

new ScalaMessage(payload)

This works. However, now ScalaMessage is not generic anymore, which might be a problem if you want use it with more refined paylods (say a Wrapper<? extends MyDerivedType>).

To fix this, let's do yet another small change to ScalaMessage:

case class ScalaMessage[T<:SomeBaseType](payload: Wrapper[_ <: T]) 

And then in java:

ScalaMessage<SomeBaseType> msg = new ScalaMessage<SomeBaseType>(payload);

Problem solved :)

like image 196
Régis Jean-Gilles Avatar answered Oct 20 '22 02:10

Régis Jean-Gilles


What you are experiencing is the fact that Java Generics are poorly implemented. You can't correctly implement covariance and contravariance in Java and you have to use wildcards.

case class ScalaMessage[T <: SomeBaseType](payload: Wrapper[T]) 

If you provide a Wrapper[T], this will work correctly and you'll create an instance of a ScalaMessage[T]

What you would like to do is to be able to create a ScalaMessage[T] from a Wrapper[K] where K<:T is unknown. However, this is possible only if

Wrapper[K]<:Wrapper[T] for K<:T

This is exactly the definition of variance. Since generics in Java are invariant, the operation is illegal. The only solution that you have is to change the signature of the constructor

class ScalaMessage[T](wrapper:Wrapper[_<:T])

If however the Wrapper was implemented correctly in Scala using type variance

class Wrapper[+T]
class ScalaMessage[+T](wrapper:Wrapper[T])

object ScalaMessage {
  class A
  class B extends A

  val myVal:Wrapper[_<:A] = new Wrapper[B]()

  val message:ScalaMessage[A] = new ScalaMessage[A](myVal)
}

Everything will compile smoothly and elegantly :)

like image 22
Edmondo1984 Avatar answered Oct 20 '22 01:10

Edmondo1984