Scala-自身类型(字符串)和将来的类型不匹配问题

问题描述 投票:0回答:2

我有一个方法,需要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
}

[MyObjectpossiblenotPossible定义:

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]

scala future
2个回答
3
投票

像这样将信息保留在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。但是在大多数情况下,这是没有必要的。


3
投票

您需要翻转方法调用:

val res: Future[???] = 
   getAction(name, surname)
     .map(bool => getData(surname, bool).id)
     .map(RequireSmth)
     .map(parse)

请注意,Future[String]不是String,它是一个将来会产生值的计算,这意味着整个计算堆栈也需要返回Future[T](除非您明确地等待,块,不推荐)。

© www.soinside.com 2019 - 2024. All rights reserved.