Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array[Nothing with java.lang.Object] required in Scala 2.9.1

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?

like image 514
Luigi Plinge Avatar asked Nov 22 '11 05:11

Luigi Plinge


1 Answers

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]
like image 119
4e6 Avatar answered Nov 20 '22 05:11

4e6