1
votes

I want to add a new implicit type class Divisible for every type T that already has either an implicit Fractional or Integral type classes.

The code I wrote does not compile:

object Divisible {

    implicit def fractionalDivisible[T](implicit frac: Fractional[T]): Divisible[T] = new Divisible[T] {
        override def div(x: T, y: T): T = frac.div(x, y)
    }

    implicit def fractionalDivisible[T](implicit integral: Integral[T]): Divisible[T]  = new Divisible[T] {
        override def div(x: T, y: T): T = integral.quot(x, y)
    }
}

trait Divisible[T] {
    def div(x: T, y: T): T
}

object Example extends App{

    def foo[T](x: T, y: T)(implicit div: Divisible[T]) = div.div(x, y)

    println(foo(1.0, 2.0))
}

The error I am receiving is:

could not find implicit value for parameter div: core.common.Divisible[Double]

If on the other hand I move the implicit def into the App, it does compile.

How can I help the compiler to find the implicit def in the companion object of Divisible?

Edit: This question had a bug.

1

1 Answers

3
votes

change the name of one of your implicit functions so they aren't both named: fractionalDivisible