Saturday, 28 September 2013

Scala working with Java libraries not specifying collections' type parameters

Scala working with Java libraries not specifying collections' type parameters

I am working with some old Java libraries that use collections not
specifying type parameters (e.g. Eclipse draw2d) in Scala.
Suppose that you have a java class (that you cannot modify) like this:
// A.java
package com.example.test;
import java.util.ArrayList;
public class A extends ArrayList {} // not ArrayList<Object>, just ArrayList
If you want to work with class A in Java, you can do this:
// B.java
import com.example.test.A;
public class B {
public static void main(String[] args) {
A a = new A();
a.add(1);
}
}
javac B.java succeed with some warnings:
Note: C.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
However, the identical thing with Scala is impossible:
// C.scala
import com.example.test.A
object C {
def main(args: Array[String]): Unit = {
val a = new A()
a.add(1)
}
}
scalac C.scala emit an error:
C.scala:6: error: type mismatch;
found : Int(1)
required: E
a.add(1)
^
How can I use this class in Scala?

No comments:

Post a Comment