Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala, can't implement generic java method

I'd like to implement a java method that uses generics in scala (2.9.2). But I'm failing...

Java interface method:

public <T extends Number> void setAttribute(Key<T> key, Number value);

Scala code that want to implement that method:

def setAttribute[T <: Number](key: Key[T], value: Number) = {
  setAttributeLocal(key, value)  }

private def setAttributeLocal[T](key: Key[T], value: T) = {
  val stringValue = ConvertUtils.convert(value, classOf[String]).asInstanceOf[String]
  session = session + (key.getValue() -> stringValue)
}

Key looks like:

public class Key<T>

But this doesn't compile.

[error]  found   : mypackage.Key[T]
[error]  required: mypackage.Key[java.lang.Number]
[error] Note: T <: java.lang.Number, but Java-defined class Key is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ <: java.lang.Number`. (SLS 3.2.10)
[error]     setAttributeLocal(key, value)

I can't figure out what's the problem. Any suggestions/idea?

greez GarfieldKlon

like image 847
GarfieldKlon Avatar asked Jul 30 '12 14:07

GarfieldKlon


1 Answers

It appears the compiler is unhappy with your call to setAttributeLocal. setAttributeLocal requires a Key[Number], but you are providing a Key[_ <: T]. In Java-Land this means you're trying to pass a Key<? extends Number> off as a Key<Number>.

The suggestion is to have setAttributeLocal accept Key<? extends Number> or Key[_ <: Number], depending on whether it is Java- or Scala-defined.

like image 195
Ben Schulz Avatar answered Nov 11 '22 09:11

Ben Schulz