Frage

I have the following class in Java:

public class GeneralClass {
    public Integer getInt(Double d) {
        return d.intValue();
    }
}

I would like to extend this class in scala e.g.

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._

class SpecializedClass extends GeneralClass {

  override def getInt(d: Double): Int = {
    d.intValue()
  }
}

The problem is that neither scala.Double nor scala.Int are automatically converted to their respective java types.

Edit The error message is:

method getInt overrides nothing. Note: the super classes of class SpecializedClass contain the following, non final members named getInt: def getInt(d: Double): Integer

Can anybody explain that and maybe point out an elegant solution?

War es hilfreich?

Lösung

getInt in SpecializedClass does not override the method in GeneralClass. To be able to override, the function argument in SpecializedClass should be contravariant and the return type to be co-variant. Which in your case is not.

So unless you have something in getInt in SpecializedClass which takes a type T :> java.lang.Double and return type as T <: java.lang.Integer, it will not override it.

For your question, actually I dont feel the need to have such a method as Scala compiler will implicitly convert Java double to Scala Double.

Andere Tipps

Try

override def getInt(d: Double): Integer = {
   return Integer.valueOf(d.intValue()); // explicit boxing
}

It does not really override an existing method (because of different types).

So one possibility is to remove the override.

On the other hand, if you really want to have the override keyword:

override def getInt(d: java.lang.Double): java.lang.Integer = {
  d.intValue()
}

Generally speaking, using primitive data types in Java/Scala interoperability can be tricky: Here is another example which deals with primitive data types together with scala.Option.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top