Skip to content

Instantly share code, notes, and snippets.

@jesperdj
Created July 11, 2010 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesperdj/471620 to your computer and use it in GitHub Desktop.
Save jesperdj/471620 to your computer and use it in GitHub Desktop.
Scala: Structural type that refers to itself
// See StackOverflow: http://stackoverflow.com/questions/3201577/scala-how-to-define-a-structural-type-that-refers-to-itself/3223088#3223088
object Example {
trait Multipliable[X] { def *(d: Double): X }
trait Addable[X] { def +(x: X): X }
trait Interpolable[X] extends Multipliable[X] with Addable[X]
implicit def double2interpolable(d: Double): Interpolable[Double] = new Interpolable[Double] {
def *(t: Double): Double = d * t
def +(j: Double): Double = d + j
}
def interpolate[X](t: Double, a: Interpolable[X], b: Interpolable[X]): Interpolable[X] = a * (1.0 - t) + b * t
def main(args: Array[String]) {
println(interpolate(0.4, 2.0, 5.0))
}
}
// C:\Temp>scalac Example.scala
// Example.scala:15: error: type mismatch;
// found : X
// required: String
// def interpolate[X](t: Double, a: Interpolable[X], b: Interpolable[X]): Interpolable[X] = a * (1.0 - t) + b * t
// ^
// one error found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment