scalauser
scalauser

Reputation: 449

How to return future from a function

I'm getting data from an API using scala's Dispatch library.

In main, I have a function getSensorList() which returns a list of sensors attached to an ID for a device.

Dispatch uses Futures to do a request Dispatch library

How do I return the future back to main?

I followed this post to implement what I have: Accessing value returned by scala futures

import dispatch._, Defaults._
import scala.util.{Success, Failure}
import scala.concurrent.duration._

def getSensorList(uuid:String) = Future[String] {

val svc = url("https://example_api.com/services/api/v1/sensors/" + uuid + "/")

val response : Future[String] = Http(svc OK as.String)

}

object DispatchTestFunction{

def main (args: Array[String]) {

val result = getSensorList("example_device_ID)

result onComplete {
  case Success(content) => {
    println("Successful response" + content)
  }
  case Failure(t) => {
    println("An error has occurred: " + t.getMessage)
  }
}
}
}

Thanks for your help.

The API returns JSON type data therefore should result be of type JSON?

The error that I have with my code is Type mismatch, expected string: actual is unit

I have the return type of the future defined as a string but the complier looks at the last line of the function and thinks it should be of type unit - i.e. that it returns notting?

Thanks

import dispatch._, Defaults._
import scala.util.{Success, Failure}


def getSensorList(uuid:String) = Future[String] {

val svc = url("https://example_api.com/services/api/v1/sensors/" + uuid + "/")

val response : Future[String] = Http(svc OK as.String)

}

object DispatchTestFunction{

def main (args: Array[String]) {

val result = getSensorList("example_device_ID")

  result onComplete {
  case Success(content) => {
    println("Successful response" + content)
  }
  case Failure(t) => {
    println("An error has occurred: " + t.getMessage)
  }
}
}
}

Upvotes: 1

Views: 4491

Answers (1)

Gábor Bakos
Gábor Bakos

Reputation: 9100

It seems I misunderstood your problem. Now it seems you had problem with the getSensorList, not how to handle the result.

Here is my take:

def getSensorList(uuid:String): Future[String] = {
    val svc = url("https://example_api.com/services/api/v1/sensors/" + uuid + "/")
    val response : Future[String] = Http(svc OK as.String)
    response
}

I have kept the response variable just in case you want to debug or further process before you return. The problem was that you just declared the result you want to return, but not returned. (= returns Unit, in Scala the assignment do not return the right hand side expression.) You are right that the Unit is kind of nothing (but not Nothing!), if you are familiar with Java/C/C++/C#, the equivalent is void (in Python it is I think None).

Upvotes: 0

Related Questions