scalagenericscontext-bound

Impose more than one generic type constraint on a Scala type parameter


I want to do the following stuff using Scala's context-bound pattern:

    class Polynomial[T: Ring] {
        def apply[X: Ring with Includes[T]](x: X): X = ...
        ...
    }

This is a polynomial class which requires the coefficients are elements in a Ring T. When applying this polynomial to a element (evaluation), the type of the parameter x is required to be a ring, and elements of type T can be implicitly cast to type X. for example T = Double, X = SquareMatrix.

How can I impose more than one type constraints to a generic type parameter in Scala?


Solution

  • It seems that [X: T] syntax is not enough for imposing two generic type constraints. Using two implicit parameters solved this problem:

       def apply[X](x: X)(implicit ring: Ring[X], conv: Includes[X, T]): X = {
         var xi = ring.one
         var sum = ring.zero
         for (i <- 0 to degree) {
           sum += xi * conv.from(coef(i))
           xi *= x
         }
        return sum
       }