Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 914
Peter Schmitz Avatar asked Oct 04 '22 05:10

Peter Schmitz


1 Answers

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
like image 65
gzm0 Avatar answered Oct 11 '22 13:10

gzm0