2011-09-06 18 views
3

這是我的第一個問題,所以希望我提供足夠的細節。隨意要求澄清。Scala:如何獲得上下文綁定List [T]轉換在這裏工作?

採取以下考慮,其工作方式:

implicit def optionBsonReader[T, U](implicit ev: BsonReader[T, U]) = new BsonReader[Option[T], Option[U]] { 
    def read(obj: Option[U]): Option[T] = { 
    obj match { 
     case Some(x) => Some(x.fromBson[T]) 
     case None => None 
    } 
    } 
} 

這段代碼BSON的選項包裹件轉換爲另一種選項[T]。我認爲,同樣會爲列出工作,但下面不編譯:

implicit def listBsonReader[T, DBObject](implicit ev: BsonReader[T, DBObject]) = new BsonReader[List[T], MongoCursor] { 
    def read(cur: MongoCursor): List[T] = { 
    cur.map(_.fromBson[T]).toList 
    } 
} 

我使用下面的代碼,一般力學:

package object bson { 

    def bsonReader[A, B](implicit reader: BsonReader[A, B]) = reader 
    def bsonWriter[A, B](implicit writer: BsonWriter[A, B]) = writer 

    implicit def addWriter[A](any: A): WithWriter[A] = new WithWriter(any) 
    implicit def addReader[A](any: A): WithReader[A] = new WithReader(any) 
} 

package bson { 
    private[bson] class WithWriter[A](any: A) { 
    def toBson[B](implicit writer: BsonWriter[A, B]): B = writer.write(any) 
    } 
    private [bson] class WithReader[B](any: B) { 
    def fromBson[A](implicit reader: BsonReader[A, B]): A = reader.read(any) 
    } 
} 

編譯器錯誤: could not find implicit value for parameter reader: project.marshalling.bson.BsonReader[T,com.mongodb.casbah.Imports.DBObject] cur.map(_.fromBson[T]).toList

這讓我覺得很奇怪,因爲它看起來像編譯器試圖評估T之前,從Bson被稱爲提供類型。這讓我感到特別奇怪,因爲期權閱讀者似乎沒有這種抱怨。我最近纔開始認真編寫Scala代碼,所以我肯定我在這裏錯過了一些東西。

請讓我知道,如果你需要更多的信息,並希望你能幫助。

最佳,

德克

+1

有些東西不太適合這裏,在你的任何引用的代碼中沒有參數'reader'。你能給出一個代碼示例以及該示例發生的確切錯誤嗎? ......在粘貼之前不需要任何編輯。 –

+0

查看編輯中的其他信息 – dlouwers

回答

2

在你listBsonReader,沒有理由類型U.上DBOBJECT你的光標迭代,地圖需要一個DbObject => X功能。我猜你有類似

implicit def withFromBson[U](x: U) = new { 
    def fromBson[T](implicit ev : BsonReader[T,U]) : T = ... 
} 

在地圖,與_類型DBObject,它是相當正常的BsonReader[T, DBObject]期待。您在隱式範圍內僅提供none,只有BsonReader[T,U]。只要刪除U並讓您的隱含參數爲BsonReader[T,DBObject]

編譯器沒有試圖預先評估T。它試圖確保無論是T還是U可能在呼叫地點(在這種情況下,U都是問題),它將隱含在隱含範圍內所需的BSonReader[T, DBObject]。我想在一般的環境中是沒有的。您用您的隱含參數承諾您將在呼叫站點提供一個BsonReader[T,U]。這不是它所需要的。如果參數不是隱含的(當調用fromBson時,您將不得不寫入ev),則會出現類似的錯誤。

+0

與BsonReader [T,DBObject]相同的問題。查看編輯的問題。 – dlouwers

+0

當然,你的DBObject類型參數隱藏了實際的DBObject,它與調用參數U沒有區別。你需要的是def listBsonReader [T],只是一個類型參數。 –

+1

你是對的!我也可以通過將_強制轉換爲DBObject來進行編譯,但這樣做會好得多。斯卡拉的類型系統很難讓我真正理解。預計它會在未來引起更多的頭痛,但是愛他們的可能性。感謝百萬人的幫助! – dlouwers

相關問題