public
Last active

Scala: Structural type that refers to itself

  • Download Gist
so-topic-3223088.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.