Implementing unsafe Java interfaces

I recently ran into a problem when developing with Spring Security. It has a GrantedAuthority interface with the following signature:

 public interface GrantedAuthority extends Serializable, Comparable 

And as for Java 1.5 and later, the Comparable interface accepts a parameter of type T , which is omitted in Spring's security libraries (obviously, for compatibility with JVM 1.4).

So, I'm trying to implement GrantedAuthority in Scala.

 class Role extends GrantedAuthority { . . . def compareTo(obj: Any): Int = obj match { case (r: Role) => r.toString.compareTo(this.toString) case _ => -1 } } 

It does not compile:

 error: class Role needs to be abstract, since method compareTo in trait Comparable of type (T)Int is not defined 

How can I implement such an interface in Scala?

+6
inheritance scala language-interoperability
source share
1 answer

Mutual issues with Java Generics come in (at least) two forms:

  • Java code that omits type arguments, as in your example, results in raw types. Comparable regarded as the existential type of Comparable[_] . Sometimes you can get rid of this problem. However, I see no way to implement def compareTo(other: _) = ... in this case.
  • Java generic files do not have the concept of a declining ad site. To extend Comparable[T] with the contravariant scala Ordering[-T] trait, an error will occur if you do not use the @uncheckedVariance annotation. ( Discussion on the mailing list )

I suggest you try upgrading to Spring 3.x, which compiled against Java 1.5. If this is not possible, write a base class BaseGrantedAuthority in Java that implements compareTo and delegates a template method that can be implemented in Scala.

+4
source share

All Articles