-1

I am trying to call one of the utility functions, but unable to return value to the caller, but somehow I am not able to return the response to the caller; i.e the main function. What could be the issue?

I tried reassigning the response to a local variable and returning that; but did not work

// 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
  }
}

Expected: The main method (caller) should get the response

Actual: The caller does not get the response after the callback returns

jwvh
  • 50,871
  • 7
  • 38
  • 64
  • 1
    This is invalid syntax. I get "error: illegal start of declaration (possible cause: missing `=' in front of current method body)". Even if the syntax were right, it wouldn't compile, as the return type of `onComplete` is `Unit`, not `GroupByResponse`. – Brian McCutchon May 08 '19 at 05:50

1 Answers1

1

Consider the following:

def f() :Unit = return 3

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

You can't return a value from a method that doesn't return a value, which is what your code is trying to do.

Look at the type signature of onComplete().

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

onComplete() appends new code to the end of a Future executing on a separate thread. The code will, eventually, be executed but onComplete() returns Unit (no useful value) to the caller right away, so your return statements are meaningless. (And poor Scala style. Don't use return. It will mislead you.)

jwvh
  • 50,871
  • 7
  • 38
  • 64
  • 2
    Also, the `fetchFromDruid` definition is missing a `=` so it will always return `Unit`. – Tim May 08 '19 at 06:25