scala self-type: member of type parameter error
Asked Answered
M

2

2

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
                               ^
Magnitude answered 23/1, 2011 at 15:59 Comment(0)
M
3

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.

Magnitude answered 24/1, 2011 at 0:34 Comment(0)
G
6

By changing the definition of - to

def -(v:V):Vec[V]
Gannet answered 23/1, 2011 at 16:33 Comment(1)
The self-type declaration is unidirectional. It says that Vec[V] is a type conforming to type V, but not that V is a type conforming to Vec[V] (the actual semantics are more involved, since self-types aren't externally visible, but that's what it amounts to here). Your original code had - returning V, but calling norm required a Vec[V].Gannet
M
3

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.

Magnitude answered 24/1, 2011 at 0:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.