Type parameter in case class using the w / Implicits attribute

Say we have a trait:

trait ThingToThing[-A, +B] { def apply(a: A): B }

and its accompanying object:

object ThingToThing {
  implicit object StringToBoolean extends ThingToThing[String, Boolean] {
    override def apply(a: String): Boolean = a.toBoolean
  }
}

and case class:

case class Thing[A](a: A) {
  def to[B](implicit thing: ThingToThing[A, B]): B = thing(a)
}

This allows me to do the following:

Thing("true").to[Boolean]
res0: Boolean = true

This is all fine and dandy, and I can do something like:

case class MyClass(ss: Seq[String]) {
  def doStuff(s: String) = Thing(s).to[Boolean]
}

But I would like, however, something like:

case class MyClass[B](ss: Seq[String]) {
  def doStuff(s: String) = Thing(s).to[B]
}

But these errors:

error: could not find implicit value for parameter thing: ThingToThing[String,B]

Is it possible to use a type parameter in mine MyClass?

** Do not fall for a toy to convert String to logical; I just used this as a simple example to illustrate the problem.

+4
source share
1 answer

The compiler could not find an implicit instance ThingToThing[String,B]( Bunknown) on the call site Thing(s).to[B]:

case class MyClass[B](ss: Seq[String]) {
  def doStuff(s: String) = Thing(s).to[B]
}

thus a mistake.

, ( B ):

case class MyClass[B](ss: Seq[String])(implicit t2t: ThingToThing[String, B]) {
  def doStuff(s: String) = Thing(s).to[B]
}

, ( B ):

case class MyClass[B](ss: Seq[String]) {
  def doStuff(s: String)(implicit t2t: ThingToThing[String, B]) = Thing(s).to[B]
}
+5

Source: https://habr.com/ru/post/1674864/


All Articles