Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala类型不匹配:必需$1,其中类型$1<;:_Scala_Generics_Type Mismatch - Fatal编程技术网

Scala类型不匹配:必需$1,其中类型$1<;:

Scala类型不匹配:必需$1,其中类型$1<;:,scala,generics,type-mismatch,Scala,Generics,Type Mismatch,我是Scala的新手,我面临着一个我无法理解和解决的问题。我写了一个通用的trait,就是这个: trait DistanceMeasure[P<:DbScanPoint] { def distance(p1:P, p2:P):Double } 然后我有以下两个类来扩展它们: class Point2d (id:Int, x:Double, y:Double) extends DbScanPoint { def getId() = id def getX() = x

我是Scala的新手,我面临着一个我无法理解和解决的问题。我写了一个通用的
trait
,就是这个:

trait DistanceMeasure[P<:DbScanPoint] {
  def distance(p1:P, p2:P):Double
}
然后我有以下两个类来扩展它们:

class Point2d (id:Int, x:Double, y:Double) extends DbScanPoint {
   def getId() = id
   def getX() = x
   def getY() = y
}

class EuclideanDistance extends DistanceMeasure[Point2d] with Serializable {

   override def distance(p1:Point2d,p2:Point2d) = {
      (p1.getX()-p2.getX())*(p1.getX()-p2.getX()) + (p1.getY()-p2.getY()) * (p1.getY()-p2.getY())
  }
}
最后我上了这门课:

class DBScanSettings {

   var distanceMeasure:DistanceMeasure[_<:DbScanPoint] = new EuclideanDistance
   //...
}
我得到以下编译错误:

 type mismatch;
 [error]  found   : it.polito.dbdmg.ontic.point.Point2d
 [error]  required: _$1 where type _$1 <: it.polito.dbdmg.ontic.point.DbScanPoint

显然,您正在进行所有相关的更改。

问题的核心是,您正在使用存在类型定义
distanceMeasure
var,因此编译器并不完全了解该类型。然后,您正在调用
distance
,这是以
P类型的两个实例为例,我需要一个很好的抽象级别,因为我希望用户在运行时动态地选择使用
DistanceMeasure
类的哪个实例……所以您提供给我的解决方案实际上不适合我的需要……有什么方法可以做到这一点吗?感谢这可能是围绕一个隐式类型类重新定义结构的一个很好的例子,该类定义了如何计算距离。然后,您可以允许隐式类型类(欧几里德立场是一种风格)在范围内的灵活性。使用这种方法,您可以定义取两个DBSCAN点的距离,并定义执行实际处理的隐式。稍后我将用一个具体的例子进行更新。
 val dbScanSettings = new DBScanSettings()
 dbScanSettings.distanceMeasure.distance(new Point2d(1,1,1), new Point2d(2,2,2))
 type mismatch;
 [error]  found   : it.polito.dbdmg.ontic.point.Point2d
 [error]  required: _$1 where type _$1 <: it.polito.dbdmg.ontic.point.DbScanPoint
trait DistanceMeasure {
  def distance(p1:DbScanPoint, p2:DbScanPoint):Double
}
trait DBScanSettings[P <: DbScanPoint] {
  val distanceMeasure:DistanceMeasure[P]
 //...
}

class Point2dScanSettings extends DBScanSettings[Point2d]{
  val distanceMeasure = new EuclideanDistance
}
val dbScanSettings = new Point2dScanSettings()
dbScanSettings.distanceMeasure.distance(new Point2d(1,1,1), new Point2d(2,2,2))