6

I have a weird compilation error. The offending lines are:

val comboBoxLanguage = new javax.swing.JComboBox
//...
comboBoxLanguage.setModel(new javax.swing.DefaultComboBoxModel( 
    Array[Object]("Scala", "Java")))

and the error:

error: type mismatch;
found   : Array[java.lang.Object]
required: Array[Nothing with java.lang.Object]
Note: java.lang.Object >: Nothing with java.lang.Object, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: Nothing with java.lang.Object`. (SLS 3.2.10)
comboBoxLanguage.setModel(new javax.swing.DefaultComboBoxModel( Array[Object]("Scala", "Java")))

According to JavaDoc the constructor of DefaultComboBoxModel expects an Object[], which can be a String[] or whatever array type in Java, since arrays are covariant, but in Scala they are not, so we have to use Array[Object], which shouldn't be a problem.

Why is the compiler expecting Array[Nothing with java.lang.Object]? How can I fix it?

This seems to be new with version 2.9.1 of Scala. My application used to compile until I installed 2.9.1 a couple of days ago. A confusing / worrying thing is that I haven't changed the project compiler library version in IntelliJ, but somehow it seems to be using it, perhaps grabbing it from my SCALA_HOME environment variable?

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180

1 Answers1

7

I think it is not an issue of scala 2.9.1 but new JDK. In JDK7 JComboBox is generic and in your code it is JComboBox[Nothing]. You should explicitly declare comboBoxLanguage variable as

val comboBoxLanguage = new javax.swing.JComboBox[Object]
4e6
  • 10,696
  • 4
  • 52
  • 62
  • Excellent, that solves it, thanks. I don't know why IntelliJ was trying to use Java 7 to compile it, as it's set to "1.6" in the Project SDK field. So I've de-selected "make" in the run configuration, and leave sbt to do the compilation using the correct Java version (6). – Luigi Plinge Nov 22 '11 at 07:16
  • @LuigiPlinge (compiling with java 7), this seems like it's a classic problem, when compiling with java 7, you're using the java 7 libraries, even if you're in compatbility mode. If you're using maven, you can look at http://mojo.codehaus.org/animal-sniffer/ – Matthew Farwell Nov 22 '11 at 09:29