Scala Type Mismatch issue when using import from different scope

守給你的承諾、 提交于 2019-12-06 05:13:21

You are using path-dependent types. They are literally dependent on paths, not on its content.

Consider that example:

class Store {
  case class Box[T](box : T)
  def box[T](b : T) = Box[T](b)
  def unbox[T](b : Box[T]) : T = b.box
}

object Assign {
  val x = new Store()
  val y = x
  val box = x.box[Int](2)
  val ub = y.unbox[Int](box)
}

You may assume naively that x and y are practically identical, they share the same content and the same type. True for the content. Wrong for types. And compiler nicely provide you with a type error:

error: type mismatch;

found : dependent.Assign.x.Box[Int]

required: dependent.Assign.y.Box[Int]

But you could tell the compiler that x and y should share the same path-dependent types despite being different literal paths

object Assign {
  val x = new Store()
  val y : x.type = x
  val box = x.box[Int](2)
  val ub = y.unbox[Int](box)
}

With val y : x.type = x the compiler would success.

Your issue has the similar nature, and the solution is similar too: you should specify type equivalence explicitly. Change the SameDAO definition to accept type parameter

class SomeDAO[MC <: MyContext](val context: MC){
  ...
}

and pass appropriate type upon creation:

class MyService(val context: MyContext){
  val someDAO = new SomeDAO[context.type](context)
  ...
}

Reduce the pain by moving the type definition to a object, therefore the type is imported statically.

Still not sure how to inherit types and how to introduce some dynamic components into this object

UPDATE: it is actually called "Path Dependent Types" in Scala.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!