Another scala type mismatch error

I am new to scala and scratching my head while trying to develop a DAO layer for my application. The following code fragment describes both the structure of the model object and the data access objects associated with them.

// 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] } 

Here is the specific use of both the model and the associated DAO.

 // example simple model object with it 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})) } 

Now that I use model objects and the associated DAO directly, life is good.

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

The problem is that I am trying to access the object as a whole. I cannot get a method signature for passing model values ​​without a compiler complaint.

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

Any help or pointers are appreciated.

+4
source share
1 answer

In all your failed procedures, the value is of type Model , but get of Column expects M You can do:

 def good[M <: Model[M]](value: M) = value.dao.columns("name").get(value) 

Avoid the existential types, when you do not need them, they complicate the situation. In addition, your Column.get may be the same as M => Any ; with covariance, it will not limit which functions are allowed.

+4
source

Source: https://habr.com/ru/post/1400069/


All Articles