javascalatwirl

Generic implementation von java.util.Comparator in Scala


I am using twirl templates with Java and Scala. So I am trying to sort a List in the template, but I do not know how to override the Comparator method.

My List contains objects of a class designed like:

class Foo extends BaseFoo<Foo>

The class BaseFoo does have a method called

public String FooName() {/*returns some Name of Foo*/}

In my scala twirl template it looks like:

source: java.util.Collection[_ <: BaseFoo[_]]

No in the twirl template I am trying to sort it:

@Collections.sort(
     new util.ArrayList[_ <: BaseFoo[_]](source),
     new Comparator[_ <: BaseFoo[_]] {
       override def compare(o1: BaseFoo, o2: BaseFoo) = {
             return o1.FooName.compareTo(o2.FooName);
       }
})

But this seems not to compile:

class type required but java.util.ArrayList[_ <: BaseFoo[_]] found


Solution

  • Not a direct answer, but given that you state that you have a list of Foo objects, the straight forward solution seems to be to use

    source: java.util.Collection[_ <: Foo[_]]
    

    or something alike!

    Meaning: when the list contains Foo objects, what does it matter if those descend from Object or from FooBase?!