如何在scala中使协变成为具有参数化返回类型的java泛型方法

如何在scala中使协变成为具有参数化返回类型的java泛型方法,scala,generics,scala-java-interop,Scala,Generics,Scala Java Interop,我试图在Scala中编写一个实现Google API Java客户端接口的凭证存储库: import com.google.api.client.auth.oauth2.StoredCredential import com.google.api.client.util.store.DataStore import com.google.api.client.util.store.DataStoreFactory class CredentialRepository extends DataS

我试图在Scala中编写一个实现Google API Java客户端接口的凭证存储库:

import com.google.api.client.auth.oauth2.StoredCredential
import com.google.api.client.util.store.DataStore
import com.google.api.client.util.store.DataStoreFactory

class CredentialRepository extends DataStore[StoredCredential] {
  ... // Implementation
}

class CredentialDataStoreFactory extends DataStoreFactory {

  val store = new CredentialRepository

  def getDataStore[V <: Serializable](id: String): DataStore[V] = store

}
如何使getDataStore协变,以便返回CredentialRepository

为什么不:

def getDataStore(id: String): DataStore[StoredCredential] = store
这应该行得通

我觉得有一个泛型
V
对我来说没有意义,因为返回的类型是定义的而不是泛型的

编辑:

如果java接口需要这样一个类型参数,您可以约束它:

def getDataStore[V <: StoredCredential with Serializable](id: String): DataStore[V] = store
def getDataStore[V为什么不:

def getDataStore(id: String): DataStore[StoredCredential] = store
这应该行得通

我觉得有一个泛型
V
对我来说没有意义,因为返回的类型是定义的而不是泛型的

编辑:

如果java接口需要这样一个类型参数,您可以约束它:

def getDataStore[V <: StoredCredential with Serializable](id: String): DataStore[V] = store

def getDataStore[V这与
DataStoreFactory
接口的约定相矛盾。
public interface DataStoreFactory{DataStore getDataStore(String id)抛出IOException;}
我得到的第一个和第三个解决方案是:
在类型的trait DataStoreFactory中重写方法getDataStore[V与第二个:
类型不匹配;找到:需要CredentialRepository:com.google.api.client.util.store.DataStore[V]注意:com.google.api.client.auth.oauth2.StoredCredential>:V(和CredentialRepository:V.(SLS 3.2.10)
一个真实的Java恐怖故事:这与
数据存储工厂
接口的契约相矛盾。
公共接口数据存储工厂{DataStore getDataStore(String id)抛出IOException;}
我得到的第一个和第三个解决方案是:
在类型的trait DataStoreFactory中重写方法getDataStore[V与第二个:
类型不匹配;找到:需要CredentialRepository:com.google.api.client.util.store.DataStore[V]注意:com.google.api.client.auth.oauth2.StoredCredential>:V(和CredentialRepository:V.(SLS 3.2.10)
一个真实的Java恐怖故事:你正在打一场败仗。问题是你必须实现的接口没有意义。你不能保证
getDataStore
将返回一个
DataStore[V]
对于世界上的任何
V
。你正在打一场失败的战争。问题是你必须实现的接口没有意义。你不能简单地保证
getDataStore
将为世界上的任何
V
返回一个
数据存储[V]