Method overload with parameterized type

Just wondering if there is a way to call an overloaded method using a parameterized type. For example, define the following object:

object Wrap {

        def f(x: X) = println("x called")
        def f(y: Y) = println("y called")
        def f(a: Any) = println("Any")

        def fp[T](t: T) = f(t)
}

When I check this, make the next call

Wrap.fp(new X())

he goes on to call Any. Is there a way that I can work so that the corresponding f is called from fp ()?

+4
source share
3 answers
def process[A](a: A) = a match {
  case c: X => Wrap f c
  case d: Y => Wrap f d
  case _ => Wrap f a 
}
+1
source

Two ways to do this:

The first method assumes that Xand Yare known types, not general types. Then you can simply do the following:

 def fp: PartialFunction[Any,Unit] ={
   case x: X => println("got x")
   case y: Y => println("got y")
   case _ => println("Any")
 }

and it will work very well without doing much finalism.

Secondly, use a class like:

 def fp[T](t: T)(implicit f: Caller[T]) = f(t)

, , , :

 trait Caller[T]{
   def apply(t: T)
 }

, Caller[Any], . :

 object Wrap{
   implicit val xCal = new Caller[X]{
     def apply(x: X){ println("x called") }
   }
   implicit val yCal = new Caller[Y]{
     def apply(x: Y){ println("y called") }
   }
 }

 object `package`{
   implicit val anyCal = new Caller[Any]{
     def apply(t: Any){ println("any") }
   }
 }
+3

:

scala> class W[A: ClassTag] { def f(x: X) = 1; def f(y: Y) = 2; def f(a: A) = 3; 
     | def g(x: Any) = x match {
     | case v: X => f(v); case v: Y => f(v); case v: A => f(v); case _ => -1 } }
defined class W

scala> trait Z
defined trait Z

scala> val w = new W[Z]
w: W[Z] = W@1685b453

scala> w g new X {}
res6: Int = 1

scala> w g new Y {}
res7: Int = 2

scala> w g new Z {}
res8: Int = 3

scala> w g "hi"
res9: Int = -1

API g , , API, Any. T OP Any, .

, , - .

+3

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


All Articles