Scala:需要类类型但找到了 T [英] Scala: class type required but T found
问题描述
我发现了这个特定问题的类似问题,但是问题是由于有人试图直接实例化 T.在这里,我试图创建一个 trait,它是一个通用接口,用于扩展类并使用 classOf[T]
将它们自动存储在 Riak 等数据库中.使用 Scala 2.10.
I've found similar issues of this particular problem, however the problem was due to someone trying to instantiate T directly. Here I'm trying to create a trait that is a general interface to extend classes and store them automatically in a database such as Riak using classOf[T]
. Using Scala 2.10.
这是我的代码:
trait RiakWriteable[T] {
/**
* bucket name of data in Riak holding class data
*/
def bucketName: String
/**
* determine whether secondary indices will be added
*/
def enable2i: Boolean
/**
* the actual bucket
*/
val bucket: Bucket = enable2i match {
case true => DB.client.createBucket(bucketName).enableForSearch().execute()
case false => DB.client.createBucket(bucketName).disableSearch().execute()
}
/**
* register the scala module for Jackson
*/
val converter = {
val c = new JSONConverter[T](classOf[T], bucketName)
JSONConverter.registerJacksonModule(DefaultScalaModule)
c
}
/**
* store operation
*/
def store = bucket.store(this).withConverter(converter).withRetrier(DB.retrier).execute()
/**
* fetch operation
*/
def fetch(id: String): Option[T] = {
val u = bucket.fetch(id, classOf[T]).withConverter(converter).withRetrier(DB.retrier).r(DB.N_READ).execute()
u match {
case null => None
case _ => Some(u)
}
}
}
编译器错误是需要类类型但找到 T
.
示例用法(伪代码):
class Foo
object Foo extends RiakWriteable[Foo]
Foo.store(object)
所以我猜测 T 的清单没有被正确定义.我需要在某处隐式定义它吗?
So I'm guessing that a manifest of T is not being properly defined. Do I need to implicitly define this somewhere?
谢谢!
推荐答案
这是一个中间解决方案,尽管它省略了 converter
注册(我可能会为此用例永久保留,目前还不确定).
Here's an intermediary solution, though it leaves out the converter
registration (which I may leave permanently for this use case, not sure yet).
/**
* trait for adding write methods to classes
*/
trait RiakWriteable[T] {
/**
* bucket name of data in Riak holding class data
*/
def bucketName: String
/**
* determine whether secondary indices will be added
*/
def enable2i: Boolean
/**
* the actual bucket
*/
val bucket: Bucket = enable2i match {
case true => DB.client.createBucket(bucketName).enableForSearch().execute()
case false => DB.client.createBucket(bucketName).disableSearch().execute()
}
/**
* store operation
*/
def store(o: T) = bucket.store(o).withRetrier(DB.retrier).execute()
/**
* fetch operation
*/
def fetch(id: String)(implicit m: ClassTag[T]) = {
val u = bucket.fetch(id, classTag[T].runtimeClass).withRetrier(DB.retrier).r(DB.N_READ).execute()
u match {
case null => None
case _ => Some(u)
}
}
}
这篇关于Scala:需要类类型但找到了 T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!