简体   繁体   中英

How to make covariant in scala a java generic method with a parameterized return type

I'm trying to write in Scala a credentials repository implementing the Google API Java client interfaces:

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

}

I'm getting this error message:

type mismatch; found : CredentialRepository required: com.google.api.client.util.store.DataStore[V]

How can I make getDataStore covariant so I can return a CredentialRepository?

Why not:

def getDataStore(id: String): DataStore[StoredCredential] = store

This should work.

I feel that having a generic V there doesn't make sense to me since the returned type is defined and not generic.

EDIT:

If the java interface needs such a type parameter, you could constrain it:

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

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM