加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

另一个scala类型不匹配错误

发布时间:2020-12-16 10:02:12 所属栏目:安全 来源:网络整理
导读:我是一个 scala新手,并一直在试图为我的应用程序开发DAO层.以下代码段概述了模型对象结构及其关联的数据访问对象. // Model object base classabstract class Model[M : Model[M]] { val dao: Dao[M]}// DAO for each model object,with find,delete,updatea
我是一个 scala新手,并一直在试图为我的应用程序开发DAO层.以下代码段概述了模型对象结构及其关联的数据访问对象.

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

任何帮助或指针将不胜感激.

解决方法

在所有不良例程中,值的类型为Model,但是Column的get期望为M.
你可以这样做:

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

当你不需要它们时避免使用存在类型,它们会使事情变得更复杂.此外,您的Column.get也可以是M =>任何;对于协方差,它不会对允许哪些功能施加任何限制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读