5

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 
1
  • 1
    For the last line to work, you need an implicit conversion from String to Int, e.g. implicitly[String => Int]—that doesn't exist. The problem here is that Y is 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. Commented May 4, 2013 at 15:30

1 Answer 1

4

Make your conversion extend Function1, then you don't need the helper method anymore:

trait Conversion[X, Y] extends (X => Y) { def apply(x: X): Y } // unchanged implicit object Str2IntConversion extends Conversion[String, Int] { def apply(s: String): Int = s.size } // removed convert // unchanged val s = "Hello" val i1: Int = convert(s) val i2: Int = s 
Sign up to request clarification or add additional context in comments.

2 Comments

Nice idea! Thank you. But the first question remains: Why is my code not working?
@PeterSchmitz probably its because of the generic return type depending on the implicit. If you replace Y with Int, your code works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.