How to invoke a method that expects a Type functio

2019-09-20 17:43发布

问题:

This is my code and I get following error when I try to invoke my m1 method:

trait Function4[-T1, -T2, -T3, -T4, +R] extends Function {
  def apply(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R
}

class Function(args: String*) extends Object {

}

class A extends Object {

  type CallbackFunction = Function4[Object, Object, Object, Object, Promise[String]]

  def m1(callback: CallbackFunction): Unit = {

  }

  def m2 = {
    m1(
      (a:Object, b:Object, c:Object, d: Object) => {
        println("good here!")
      }
    )
  }
}

Error is : Type mismatch, expected: A.this.CallbackFunction, actual: (Object, Object, Object, Object) => Promise[String]

回答1:

Actually your original code (revision 1) works fine in Scala 2.12, not work in Scala 2.11.

If you want you code work in Scala 2.11 you can rewrite code like this:

class A extends Object {

  type CallbackFunction[A] = Function4[Object, Object, Object, Object, A]

  def m1[A](callback: CallbackFunction[A]): Unit = {

  }

  def m2 = {
    m1(
      (a:Object, b:Object, c:Object, d: Object) => {
        println("good here!")
      }
    )
  }
}

Or change Function4[Object, Object, Object, Object, _] to Function4[Object, Object, Object, Object, Unit].

If you want you current code (revision 2) work, you only need to change Promise[String] to Unit.



回答2:

Why is your code defining your own Function (which doesn't describe a function) and your own Function4 (when there is one in the standard library)?

If, as your comment to another answer says, "I can not change anything in my CallbackFunction, this is a library code", this very much looks like a library nobody should be using.

However, the direct answer to your question is that the argument you pass to m1 must be a function returning Promise[String]. Assuming Promise is the standard scala.concurrent.Promise instead of another type defined by the library, one possibility would be

  (a:Object, b:Object, c:Object, d: Object) => Promise()

But that would only make it compile (so would passing null!); it isn't at all clear what you want to do.



标签: scala