2014-06-11 42 views
2

我发现了这个特定问题的类似问题,但问题是由于有人试图直接实例化T。在这里,我试图创建一个通用接口来扩展类,并将它们自动存储在使用classOf[T]的Riak等数据库中。使用Scala 2.10。Scala:需要类的类型但T找到了

这里是我的代码:

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) 
    } 
    } 

} 

编译器错误是class type required but T found

实施例使用(伪码):

class Foo 

object Foo extends RiakWriteable[Foo] 

Foo.store(object) 

所以我猜测,T的清单未被正确限定。我需要隐式定义这个地方吗?

谢谢!

回答

1

下面是一个中介解决方案,虽然它不包含converter注册(我可能会永久保留此用例,但尚不确定)。

/** 
* 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) 
    } 
    } 

} 
相关问题