开发者

scala self-type: member of type parameter error

开发者 https://www.devze.com 2023-02-06 19:50 出处:网络
This is a followup to this question. Why does this code not compile, and how do I fix it? trait Vec[V] { self:V =>

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
                               ^


By changing the definition of - to

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消