无法将值返回给调用方函数scala

时间:2019-05-08 02:31:35

标签: scala druid

我正在尝试调用一个实用程序函数,但无法将值返回给调用方,但是以某种方式我无法将响应返回给调用方;即主要功能。可能是什么问题?

我尝试将响应重新分配给局部变量,然后将其返回;但没有用

// main function
def main(args: Array[String]): Unit = {
  val res = fetchFromDruid()
  // res comes as null here
}

def fetchFromDruid(): GroupByResponse {
  // creating an execution context

  // creating a local druid client

  // constructing a group by query

  // executing the query
  client(query).onComplete {
    //this will be executed if data is fetched successfully
    case Success(response) =>
      return response

    //this will be executed if there is an exception
    case Failure(ex) =>
      ex.printStackTrace()
      return null
  }
}

预期:主方法(调用方)应获得响应

实际:回调返回后,呼叫者未获得响应

1 个答案:

答案 0 :(得分:1)

请考虑以下内容:

def f() :Unit = return 3

val x = f()  //x: Unit = ()

您不能从不返回值的方法中返回值,这就是您的代码要尝试执行的操作。

查看onComplete()的类型签名。

abstract def onComplete(f: (Try[T]) ⇒ U)(executor: ExecutionContext): Unit

onComplete()将新代码附加到在单独线程上执行的Future的末尾。该代码最终将被执行,但是onComplete()立即向调用方返回Unit(无用值),因此您的return语句毫无意义。 (还有糟糕的Scala风格。不要使用return。它会误导您。)

相关问题