2014-06-11 63 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) 
    } 
    } 

} 
相關問題