How to call an overloaded method from a generic type

I have this set of overloaded functions:

case class A[T](t: T)

object C {
   def dump(a: A[String], s: String) = ....
   def dump(a: A[Int], s: Int) = ....
   def dump(a: A[Double], s: Double) = ....
}

and have this common method:

class B {
   def dump[T](a: A[T], t: T) = C.dump(a, t)
}

It does not compile, because the Scala compiler gets confused with various overloads. What is the right way to do this?

+4
source share
2 answers

Based on @drexin's answer using ad-hoc polymorphism, I just slightly modified the use of the question's signature to make it clearer.

def dump[T](a: A[T], t: T) = C.dump(a, t)

case class A[T](t: T)
trait Dumper[T] {
  def dump(a: A[T], t: T): Unit
}
class B {
  def dump[T](a: A[T], t: T)(implicit dumper: Dumper[T]) = dumper.dump(a, t)
}
implicit val IntDummper = new Dumper[Int] {
  override def dump(a: A[Int], t: Int): Unit = {
    println("int dummper processing it")
  }
}

implicit val StringDummper = new Dumper[String] {
  override def dump(a: A[String], t: String): Unit = {
    println("string dummper processing it")
  }
}

val result = new B

result.dump(A("3"), "3") //string dummper processing it
result.dump(A(3), 3) //int dummper processing it
+1
source

edit: , , C.dump , , - T, , .


ad-hoc-:

trait Dumper[A] {
  def dump(a: A): Unit
}

case class A[T](t: T)

object A {
  implicit object AStringDumper extends Dumper[A[String]] {
    def dump(a: A[String]) = println(s"String: $a")
  }

  implicit object ADoubleDumper extends Dumper[A[Double]] {
    def dump(a: A[Double]) = println(s"Double: $a")
  }
}

object C {
  def dump[A](a: A)(implicit dumper: Dumper[A]) = dumper.dump(a)
}

C.dump Dumper[A]. , :

scala> C.dump(A("foo"))
String: A(foo)

scala> C.dump(A(1.2))
Double: A(1.2)

scala> C.dump(A(1))
<console>:17: error: could not find implicit value for parameter dumper: Dumper[A[Int]]
              C.dump(A(1))
+6

Source: https://habr.com/ru/post/1548325/


All Articles