Search code examples
scalathissubtype

Scala : Force the type of some function to use the type of this in a trait


I am trying to define the following trait in a meaningful way

trait Summable {
    def +(that: Summable): Summable
}

But I would like the type of that to be the same as the type of this, so if A is Summable for instance, then we want the + to work only if that is of the type A and not any other Summable.

I could not find anyway of doing that in the doc, if someone have any idea or document I could read about that, I would be glad.


Solution

  • You are looking for F bound polymorphism

    trait Summable[A <: Summable[A]] { self: A =>
        def +(that: A): A
    }
    

    Now, you can creat a concrete implementation like following,

    class IntSummable(val i: Int) extends Summable[IntSummable] {
      override def +(that: IntSummable): IntSummable = new IntSummable(this.i + that.i)
    }
    
    val is1 = new IntSummable(5)
    val is2 = new IntSummable(10)
    
    val is3 = is1 + is2
    

    But something like following will not compile,

    class DoubleInvalidSummable1(val d: Double) extends Summable[DoubleInvalidSummable1] {
      override def +(that: IntSummable): DoubleInvalidSummable1 = new DoubleInvalidSummable1(this.d + that.i)
    }