Why is the following implicit method not applied? And how can I achieve to automatically convert an instance of X to an instance of Y while having an implicit Conversion[X,Y] in scope.
trait Conversion[X, Y] { def apply(x: X): Y } implicit object Str2IntConversion extends Conversion[String, Int] { def apply(s: String): Int = s.size } implicit def convert[X, Y](x: X)(implicit c: Conversion[X, Y]): Y = c(x) val s = "Hello" val i1: Int = convert(s) val i2: Int = s // type mismatch; found: String required: Int
StringtoInt, e.g.implicitly[String => Int]—that doesn't exist. The problem here is thatYis a parameter, and Scala won't just substitute that to whatever type you are looking for. For example,implicit def convert[X](x: X)(implicit c: Conversion[X, Int]): Int = c(x)would work.