Scala - how to define a structural type that refers to itself?

孤街浪徒 提交于 2019-11-28 07:03:15

Surely you could solve this problem using the typeclasses approach (of e.g. Scalaz):

trait Multipliable[X] {
  def *(d : Double) : X
}

trait Addable[X] {
    def +(x : X) : X
}

trait Interpolable[X] extends Multipliable[X] with Addable[X]

def interpolate[X <% Interpolable[X]](t : Double, a : X, b : X)
    = a * (1.0 - t) + b * t

Then obviously you would need a (implicit) typeclass conversion in scope for all the types you cared about:

implicit def int2interpolable(i : Int) = new Interpolable[Int] {
  def *(t : Double) = (i * t).toInt
  def +(j : Int) = i + j
}

Then this can be run easily:

def main(args: Array[String]) {
  import Interpolable._
  val i = 2
  val j : Int = interpolate(i, 4, 5)

  println(j) //prints 6
}
Daniel C. Sobral

AFAIK, this is not possible. This was one of my own first questions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!