4
我是一個scala新手,一直在試圖爲我的應用程序開發一個DAO層。以下代碼片段概述了模型對象結構及其關聯的數據訪問對象。又一個scala類型不匹配錯誤
// Model object base class
abstract class Model[M <: Model[M]] {
val dao: Dao[M]
}
// DAO for each model object, with find, delete, update
abstract class Dao[M <: Model[M]] {
// meta data describing the model object
case class Column(val name:String, val get: M => _)
val columns : Map[String,Column]
}
下面是模型及其關聯的DAO的具體使用。
// example simple model object with it's DAO
case class ItemModel (val name:String) extends Model[ItemModel] {
val dao = ItemDao
}
object ItemDao extends Dao[ItemModel] {
val columns = Map("name" -> Column("name", { v:ItemModel => v.name}))
}
現在,當我使用模型對象,它直接關聯DAO,生活是美好的。
object Works {
// normal access pattern
def good1(value: ItemModel) = value.name
// even through the DAO
def good2(value: ItemModel) = value.dao.columns("name").get(value)
}
問題是當我試圖訪問一個對象一般。如果沒有編譯器抱怨,我無法獲得用於傳遞Model值的方法簽名。
// Trouble trying to manipulate base model objects
object Trouble {
// type mismatch; found : value.type (with underlying type test.Model[_]) required: _$2 where type _$2 Test.scala
def bad1(value: Model[_]) = value.dao.columns("name").get(value)
// type mismatch; found : value.type (with underlying type test.Model[_ <: test.Model[_]]) required: _$3 where type _$3 <: test.Model[_]
def bad2(value: Model[_ <: Model[_]]) = value.dao.columns("name").get(value)
// type mismatch; found : value.type (with underlying type X forSome { type X <: models.Model[X] }) required: X where type X <: models.Model[X]
def bad3(value: X forSome {type X <: Model[X]}) = value.dao.columns("name").get(value)
}
任何幫助或指針將不勝感激。
謝謝你的工作。你這個人! – 2012-03-06 18:26:03