Search code examples
scalaimplicit-conversionimplicitimplicitsscala-implicits

Implicit conversions in generic function


I need to convert from Any to basic numeric types like Int or Double. I implemented these conversions by using Scala implicits. My code is similar to this one:

  def convertAny[T](any: Any)(implicit run: Any => Option[T]) = run.apply(any)
  implicit def anyToDouble(any: Any) = Try(any.asInstanceOf[Double]).toOption
  implicit def anyToInt(any: Any) = Try(any.asInstanceOf[Int]).toOption

The problem is that I need to do these conversions inside a generic function like this one:

  def doStuffAndConvert[T](i: Any): Option[T] = {
    // Some pre-processing
    println("Processing data...")

    convertAny[T](i)
  }

This is the call to doStuffAndConvert:

doStuffAndConvert[Double](a)

However, the compiler throws this error:

Error:(40, 18) No implicit view available from Any => Option[T].
    convertAny[T](i)

I tried to help the compiler by wrapping the Int and Double types and bounding the Tgeneric type, but it didn't work.

How could I fix it?

Thanks.


Solution

  • You need to add the implicit argument convertAny needs to doStuffAndConvert as well:

    def doStuffAndConvert[T](i: Any)(implicit run: Any => Option[T]): Option[T] = {
      // Some pre-processing
      println("Processing data...")
    
      convertAny[T](i) // or just i, the implicit will be used anyway
    }
    

    Implicits like anyToDouble/Int look suspicious to me, but this may just be a kneejerk reaction.