Skip to content

@jesperdj /so-topic-3223088.scala
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.