Need help with calling and returning value from function in scala

#1

I am trying to call function fetchFromDruid

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

def fetchFromDruid(): GroupByResponse {
implicit val executionContext = ExecutionContext.Implicits.global
val client = DruidClient(“http://localhost:8082”)

val query = GroupByQuery(
source = “wikipedia”,
interval = new Interval(new DateTime().minusMonths(60), new DateTime()),
dimensions = Seq(“countryName”),
descending = true,
granularity = Granularity.All,
aggregate = Seq(
DSL.count(“row_count”)
),
postAggregate = Seq(
),
limit = Some(100)
)

client(query).onComplete {
case Success(resp) =>
resp.data.foreach { row =>
println(row)
}
return resp
println(“none”)
//System.exit(0)
case Failure(ex) =>
ex.printStackTrace()
return null
//System.exit(0)
}
}

But somehow I am not able to return the response to the caller; i.e the main function. What could be the issue?

Thanks,
Tushar

#2

It would make it easier for folks to help you out if you format your code here. Before and after your code, put a line with just three backticks at the beginning of the line and nothing else: ``` – that will make it come out formatted.

That said, the short version is probably that you can’t use Futures like that – I don’t know what GroupByResponse does, but the code’s pretty suspicious. You’re trying to get a response synchronously from fetchFromDruid(), but that’s an asynchronous method. You either have to block using Await and get the result when it is done (which I strongly discourage: it will work, but it’s bad practice and hugely destructive of any sort of serious program), or (better) you need to return the Future and use .map() to say what to do when it completes.

But onComplete doesn’t do what you think it does. Your function probably isn’t returning null (which you should really never use in Scala code), it’s likely returning Unit – basically, the function doesn’t do anything synchronously, and the Future isn’t complete yet when it returns. The onComplete only fires when the Future actually finishes, which is probably long after the function returns, on a different thread…