Given a made-up F type-class:
scala> trait F[A] {} defined trait F and this definition, which uses a context bound to require that the input A has a type-class instance of F:
scala> def f[A : F](x: A) = ??? f: [A](x: A)(implicit evidence$1: F[A])Nothing I defined a Person and type-class instance:
scala> case class Person(name: String) defined class Person scala> implicit val person: F[Person] = new F[Person] {} person: F[Person] = $anon$1@262b2c86 And the following compiles:
scala> f(Person("foo")) scala.NotImplementedError: an implementation is missing But, there's no String implementation, so it fails.
scala> f("foobar") <console>:17: error: could not find implicit value for evidence parameter of type F[String] f("foobar") ^ I then defined an F[String] using:
scala> implicit def fInstance(x: String) = new F[String] {} fInstance: (x: String)F[String] But, I can't run:
scala> f("foobar") <console>:18: error: could not find implicit value for evidence parameter of type F[String] f("foobar") ^ since I do not have an implicit F[String], but rather a String => F[String].
What's the proper way to use such an implicit def to meet the F[String] constraint, i.e. call the f function successfully with a type of String?
I got it to work via:
scala> implicit val x: F[String] = implicitly[String => F[String]].apply("foobar") x: F[String] = $anon$1@7b7fdc8 scala> f("foobar") scala.NotImplementedError: an implementation is missing at scala.Predef$.$qmark$qmark$qmark(Predef.scala:230) at .f(<console>:12) ... 33 elided But I'm not sure if it's the right/clean way to do it.
F, you could define aStringinstance in exactly the same way you did thePersoninstance.F[String]if provided aString, i.e. anF[String]instance depends upon aStringargument.implicitoutside of a companion class, i.e. an orphanimplicitinstance?fInstanceis not a typeclass instance, but an implicit conversion