Created
July 11, 2010 15:13
-
-
Save jesperdj/471620 to your computer and use it in GitHub Desktop.
Scala: Structural type that refers to itself
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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