Can it implicate a change in the multiplicity of a parameter on a call node?

My API prototype is as follows:

I have a third-party API object with a name ZResponseHandlerthat has a method

printZ(z:Z) 

no I have the following:

case class X
case class Y 
case class Z(x:X,y:Y)

now when i use my API calling printZ method with new instance of z, it works fine.

ZResponseHandler.printZ(new Z(x,y))

but I would like to create something like this:

implicit def convertXYtoZ(x:X,y:Y):Z = new Z(x,y)

ZResponseHandler.printZ(x,y)

this code gives me a compilation error - too many arguments for method printZ:

is there any way to make some implicit class that accept printZ (x, y)?

+4
source share
2 answers

Implicits can use the wrap or "pimp" of the recipient to decorate it with more methods.

class R {
  def m (s: String) = println(s)
}

// This uses an anonymous type, but it could also return
// `new RichR(r)` or similar as appropriate.
implicit def toRichR(r: R) = new {
    def m(a: String, b: String) = r.m(a + " " + b)
}

val r = new R()
r.m("hello", "world") // -> toRichR(r).m("hello", "world")

(Scala 2.10+) .

implicit class RichR(r: R) {
    def m(a: String, b: String) = r.m(a + " " + b)
}

"" Scala 2.10 ( 2.8)

object R {
  def m (s: String) = println(s)
}

// uses TheObject.type
implicit def toRichR(_r: R.type) = new {
    // (could use _r.m instead of R.m)
    def m(a: String, b: String) = R.m(a + " " + b)
}

R.m("hello", "world") // -> toRichR(r).m("hello", "world")

( , [non-object].)

+2

, arity ( ). Tuple:

implicit def convertXYtoZ(t: (X,Y) ):Z = new Z(t._1, t._2)
ZResponseHandler.printZ(x,y)
+2

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


All Articles