Peter Schmitz
Peter Schmitz

Reputation: 5844

Implicit conversion not working

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

Upvotes: 5

Views: 321

Answers (1)

gzm0
gzm0

Reputation: 14842

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

Upvotes: 4

Related Questions