scala self-type: member of type parameter error

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 16:07:33

问题


This is a followup to this question.

Why does this code not compile, and how do I fix it?

trait Vec[V] { self:V =>
  def -(v:V):V
  def dot(v:V):Double

  def norm:Double = math.sqrt(this dot this)
  def dist(v:V):Double = (this - v).norm
}

The error is:

Vec.scala:6: error: value norm is not a member of type parameter V
  def dist(v:V):V = (this - v).norm
                               ^

回答1:


By changing the definition of - to

def -(v:V):Vec[V]



回答2:


The proper solution is:

trait Vec[V <: Vec[V]] { self:V =>
  def -(v:V):V
  def dot(v:V):Double

  def norm:Double = math.sqrt(this dot this)
  def dist(v:V):Double = (this - v).norm
}

Props to Debilski for the answer to a related question.



来源:https://stackoverflow.com/questions/4774743/scala-self-type-member-of-type-parameter-error

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