goo
goo

Reputation: 2280

Scala: "required: scala.concurrent.Future[?]"

Edit

Still haven't found a solution so I ended up creating two someFuture methods. One that returns a future & one that doesn't (to get otherFuture to compile)


I'm trying to return Future[Option[JsObject]] but keep getting this error:

required: scala.concurrent.Future[?]

What I'm doing

def someFuture:Future[Option[JsObject]] =
  Future {
    Option(JsObject())
  }

def otherFuture:Future[Option[JsObject]] =
  Future {
    Option(JsObject(
      someFuture.flatMap(_.get)
    ))
  }

// get error here
found   : JsObject
[error]  required: scala.concurrent.Future[?]

How can I return the JsObject without getting an error?

Upvotes: 3

Views: 1903

Answers (1)

Travis Brown
Travis Brown

Reputation: 139028

The problem is that someFuture.flatMap(_.get) won't compile—you need to provide a function that takes a JsObject and returns a Future[Whatever] to use flatMap on someFuture.

You probably want something like this:

def otherFuture: Future[Option[JsObject]] = someFuture.map { opt =>
  Option(JsObject(opt.get))
}

There's not really any reason to use Option if you're just going to call .get on it like this, though, so the following might be better:

def otherFuture: Future[Option[JsObject]] = someFuture.map(_.map(JsObject(_)))

Now if the future is satisfied by a non-empty option, the contents of the option will be wrapped in another layer of JsObject, which seems to be what you're aiming for?

Note that if you're using Option to represent failure, you may want to consider the failure-handling that's built into Future instead.

Upvotes: 4

Related Questions