case class Cat(name: String)
object CuterImplicits {
implicit class CatCuteChecker(c: Cat) {
def isCute(c: Cat) = true
}
}
trait CuteChecker[A] {
def isCute(a: A): Boolean
}
object CheckingForCuteness {
def isItCute[A](a: A) = implicitly[CuteChecker[A]].isCute(a)
}
object Main extends App {
CheckingForCuteness.isItCute[Cat](Cat("funny"))
}
how to fix:
Error:(17, 37) could not find implicit value for parameter e: CuteChecker[A] def isItCute[A](a: A) = implicitly[CuteChecker[A]].isCute(a) ^
If you use implicitly
that simply makes a value implicitly in scope "explicitly" available. So your isItCute
method should be either of the following two variants:
def isItCute[A: CuteChecker](a: A) = implicitly[CuteChecker[A]].isCute(a)
def isItCute[A](a: A)(implicit cc: CuteChecker[A]) = cc.isCute(a)
Next you want an implicit instance for Cat
. The implicit class
doesn't help you here because it requires a non-implicit value of type Cat
. You can see that this approach is wrong because the constructor parameter is never used. You can use an implicit object
:
implicit object CatCuteChecker extends CuteChecker[Cat] {
def isCute(c: Cat) = true
}
Finally, you provide implicits in object CuterImplicits
. For them to be visible to Main
, you need to import the contents:
object Main extends App {
import CuterImplicits._
CheckingForCuteness.isItCute[Cat](Cat("funny"))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With