Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

could not find implicit value for parameter e

Tags:

scala

implicit

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) ^

like image 585
Jas Avatar asked Dec 25 '15 20:12

Jas


1 Answers

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"))
}
like image 93
0__ Avatar answered Sep 22 '22 19:09

0__