简体   繁体   中英

Implicit def type classes from other type classes

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.

更改其中一个隐式函数的名称,因此它们不会同时命名:fractionalDivisible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM