开发者

Return a Java collection of type and subclasses from Scala

开发者 https://www.devze.com 2023-02-03 15:23 出处:网络
I have an interface in Java that looks something like this: public interface X<T> { Set<Class<? extends T>> getTypes();

I have an interface in Java that looks something like this:

public interface X<T> {
  Set<Class<? extends T>> getTypes();
}

I need to implement this interface in Scala 2.8 and currently I'm doing something like this:

class XImpl extends X<CacheValue> {
  override def getTypes = {
    val set = asJavaSet(Set(classOf[CacheValue]))
    set
  }
}

But this does not compile and the compiler says:

error: type mismatch;
found   : java.util.Set[java.lang.Class[CacheValue]]
required: java.util.Set[java.lang.Class[_ <: CacheValue]]开发者_如何学Python
set

Any idea how to get around this issue?

UPDATE:

I've tried the following but still no luck:

  override def getTypeClasses = {
     val set = asJavaSet(Set(classOf[CacheValue].asSubclass(classOf[CacheValue])))
     set
  }

In this latter case I get:

error: type mismatch;
found   : java.util.Set[java.lang.Class[?0]] where type ?0 <: org.infinispan.server.core.CacheValue
required: java.util.Set[java.lang.Class[_ <: org.infinispan.server.core.CacheValue]]
set


As the compiler says, the automatically inferred type is java.util.Set[java.lang.Class[CacheValue]], but it should work if you annotate the type explicitly:

class XImpl extends X[CacheValue] {
  override def getTypes = {
    val set = asJavaSet(Set(classOf[CacheValue]: java.lang.Class[_ <: CacheValue]))
    set
  }
}

EDIT: try this then:

class XImpl extends X[CacheValue] {
  override def getTypes = {
    val set = asJavaSet(Set[java.lang.Class[_ <: CacheValue]](classOf[CacheValue]))
    set
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号