我有一个方法,它需要String
类型作为参数:
type Identity = String
case class RequireSmth(param: Identity) extends Something
现在我以更复杂的顺序称这种方法:
createMe(as[List])(arg =>{ parse(RequireSmth(getAction(name, surname).map(bool => getData(surname, bool).id))) })
Parse
看起来像:
def parse(ob: Something)
其中:
def getAction(name: String, surname: String): Future[Boolean] = {
someObject.get(name).map(_.getSomething(surname).isPossibleToTake.getOrElse(false)) //someObject is defined in constructor and does not matter here
}
def getData: (String, Boolean) => MyObject = {
case ("Doe", true) => possible
case _ => notPossible
}
MyObject
、possible
和notPossible
的定义:
case class MyObject(id : String, name: String, surname: String)
val possible = MyObject( id = "ok", name ="John", surname = "Doe")
val notPossible = MyObject( id = "not ok", name ="John", surname = "Doe")
问题是,当我调用RequireSmth
方法时,我得到了一个错误:
type mismatch;
found: scala.concurrent.Future[String]
required: com.my.smth.Identity (which expands to) String
如何解决返回Identity
(或String
(而不是Future[String]
的问题?
将信息保存在Future
中,如下所示:
getAction(name, surname).map(bool => getData(surname, bool).id).map(RequireSmth)
只需将操作链接在一起,将所有内容都保存在Future
:中
getAction(name, surname)
.map(bool => getData(surname, bool).id)
.map(RequireSmth) // Or x => RequireSmth(x) if necessary
.map(parse)
在某个时刻,您将获得一个具有副作用并返回Unit
的方法,该方法将在Future
中的所有操作完成后执行。
在实际需要从Future
中获取值的不太可能的情况下,请使用Await.result
。但在大多数情况下,这是没有必要的。
您需要翻转方法调用:
val res: Future[???] =
getAction(name, surname)
.map(bool => getData(surname, bool).id)
.map(RequireSmth)
.map(parse)
请注意,Future[String]
不是String
,它是一个将来会产生值的计算,这意味着整个计算堆栈也需要返回Future[T]
(除非您明确等待,否则会阻塞,不建议使用(。