我在Scala上很新手,我正在尝试将泛型类型传递到隐式类中,但我找不到方法。
下面是我的隐式类
object Utils{
implicit class cacheUtils[T:ClassTag](cache:CacheApi){
def getVal(key:String): T = cache.get(key).get
}
}以及我是如何调用
import implicits.Utils.cacheUtils
Test @Inject()(cache: CacheApi) extends Controller {
val xxx: List[X] = cache.getVal(xx.asString)
}但显然,他需要的是T类型,而不是List[X]类型
你知道怎么做到这一点吗?
致以问候。
发布于 2016-09-17 21:04:32
看起来你的代码中有两个问题。
CacheApi应该是具有T类型的参数,这意味着它应该看起来像这样:class CacheApi[T](...),并且您的cacheUtils类参数应该是cache: CacheApi[T]而不是cache: CacheApi 编辑
根据OP的请求,下面是一个完整的示例:
class CacheApi[T](list: List[T]) {
def get = list.head
}
object Utils {
implicit class cacheUtils[T](cache: CacheApi[T]) {
def getVal(key: String): T = cache.get
}
}
import Utils._
val cacheStrings = new CacheApi(List("hello"))
val cacheLists = new CacheApi(List(List(42)))
val s: String = cacheStrings.getVal("")
val list: List[Int] = cacheLists.getVal("")https://stackoverflow.com/questions/39546480
复制相似问题