Need help with calling and returning value from function in scala

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 =
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(
postAggregate = Seq(
limit = Some(100)

client(query).onComplete {
case Success(resp) => { row =>
return resp
case Failure(ex) =>
return null

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


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…

Sure. Thanks for the response @jducoeur