I want to use a Java library in my Scala program. The library contains a generic class which is part of other classes:
package java.items;
public class Item<T extends Comparable> implements Comparable<Item> {
private T id;
...
}
public final class Itemset{
private List<Item> items = new ArrayList<Item>();
public List<Item> getItems() { return items; }
...
}
public class Sequence {
private final List<Itemset> itemsets = new ArrayList<Itemset>();
public List<Itemset> getItemsets() { return itemsets; }
...
}
In my Scala code, I loop over the different objects and need to instantiate a hashmap of type [T, Int]
to store the Ids with a counter:
import java.items._
object ConvertSequence {
def ConvertSequence (dataset: RDD[(Sequence)], sc: SparkContext) {
sc.broadcast(dataset.flatMap(r => {
val itemCounts = new HashMap[AnyRef, Int]
for (itemset <- r.getItemsets) {
for (item <- itemset.getItems) {
val i = itemCounts.getOrElse(item.getId, 0)
itemCounts.update(item.getId, i + 1)
}
}
itemCounts
}).
map(r => (r._1, (r._2, 1))).
reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2)).
sortBy(r => (r._2._1, r._1))
zipWithIndex().
collect({ case (k, v) => (k._1, v)})
)
}
I don't know which type to pass to the hashmap constructor (T
is not available from my Scala object as only Item
is typed).
I've tried AnyRef
but I get a error at compilation:
[ERROR] error: type mismatch;
[INFO] found : ?0
[INFO] required: AnyRef
[INFO] Note that ?0 is unbounded, which means AnyRef is not a known parent.
[INFO] Such types can participate in value classes, but instances
[INFO] cannot appear in singleton types or in reference comparisons.
[INFO] val i = itemCounts.getOrElse(item.getId, 0)
[INFO] ^
[ERROR] one error found
How can I manage polymorphism between my Java and Scala code?