简体   繁体   中英

Convert method override with wildcard from Java to Scala

I have a Java method signature that I can't seem to convert to a signature in Java.

Here is the Java code:

public class InjectorListCellRenderer extends DefaultListCellRenderer {
  public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    throw new RuntimeException("not important");
  }  
}

And here the Scala code which I hoped would be equivalent:

class InjectorListCellRenderer(var painter: ParticleLabelPainter) extends DefaultListCellRenderer {
  override def getListCellRendererComponent(list: JList[_], value: Any, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component = {
    throw new RuntimeException("not important")
  }
}

However when compiling with sbt and Scala 2.11.8 I get the following error:

class InjectorListCellRenderer needs to be abstract, since method getListCellRendererComponent in trait ListCellRenderer of type (x$1: javax.swing.JList[_ <: Object], x$2: Object, x$3: Int, x$4: Boolean, x$5: Boolean)java.awt.Component is not defined

The documentation for the base class DefaultListCellRenderer can be found here .

I can't seem to reproduce this problem with my own code.

Starting from the error message I would guess the following should work:

class InjectorListCellRenderer(var painter: ParticleLabelPainter) extends DefaultListCellRenderer {
  override def getListCellRendererComponent(list: JList[_ <: AnyRef], value: AnyRef, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component = {
    throw new RuntimeException("not important")
  }
}

Edit: after some experimentation I think that inheriting from DefaultListCellRenderer and overriding getListCellRendererComponent is not possible due to some inconsistency between Java's and Scala's type representations. If this is important to you you might consider filing a bug report.

Its saying the type of the JList argument isnt the same because you've left it as a hole [_] but it expects at least object.

Seems to work if you put object , any or make it parametric with T .

class InjectorListCellRenderer() extends DefaultListCellRenderer{
   def getListCellRendererComponent(list: JList[Object], value: Any, index: Int, isSelected: Boolean, cellHasFocus: Boolean) = ???
}

or

class InjectorListCellRenderer() extends DefaultListCellRenderer{
   def getListCellRendererComponent[T](list: JList[T], value: Any, index: Int, isSelected: Boolean, cellHasFocus: Boolean) = ???
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM