函数 return 类型错误 future.onComplete

Function return type error with future.onComplete

我正在使用 Scala

我有一个方法 returns 一个对象,在这个方法中我使用 future with onComlpete 回调

def xyzFunction (id : Int) : Abc = {

var abcObj = new Abc
 var RetunedLists = new MutableList[ArtistImpl]()
val future:Future[MutableList[Abc]] = ask(SomeActor,Message(id)).mapTo[MutableList[Abc]]
        future.onComplete {
         case Success(result) =>
           RetunedLists = result
           abcObj = RetunedLists.get(0)
          println("name : " + abcObj.name)


         case Failure(e) =>
        println("printStackTrace"+e.printStackTrace)


    }
 abcObj
}

问题是当我 运行 它在控制台上打印名称的代码 bt 这个函数的对象是空的

请帮帮我!

问题是 xyzFunction 完成时,未来尚未完成。这意味着 abcObj 尚未设置(在 future.onComplete 块中),因此它仍然等于其初始值(来自 var abcObj = new Abc 行)。

为确保 xyzFunction return 是 abcObj 的有效值,您可以等待将来完成(例如通过 Await.result(future, timeoutValue))。

不过,更好的方法是 return a Future[Abc],将结果链接为期货(使用 mapflatMap 和类似方法)一直向上线路并尽可能晚地解决。例如,如果使用 Play 框架,请使用 Action.async 并让 Play 在内部为您解决未来的问题。