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

前端 未结 2 1295
夕颜
夕颜 2020-12-09 00:06

I\'m trying to write a generic interpolate method that works on any type that has two methods, a * and a +, like this:



        
相关标签:
2条回答
  • 2020-12-09 00:35

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

    0 讨论(0)
  • 2020-12-09 00:39

    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
    }
    
    0 讨论(0)
提交回复
热议问题