简体   繁体   中英

Pass generic type to a generic method in scala

I have written a function

def getOptional[A](key: String) : Option[A] = {
   redisClients.withClient(redisClient =>
      redisClient.get[A](key)
   )
}

and I am calling it

redis.getOptional[List[Long]](REDIS_PREFIX_PRODUCT_IDS)

but this throws an exception

could not find implicit value for parameter parse: com.redis.serialization.Parse[A][error] redisClient.get[A](key)

What is the issue here?

The get requires an additional implicit parameter Parse[A] . If there is no Parse[A] , then it's unclear what to parse, because the type A is erased at runtime. Try this instead:

import com.redis.serialization.Parse
def getOptional[A: Parse](key: String) : Option[A] = {
  redisClients.withClient(redisClient =>
    redisClient.get[A](key)
  )
}

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