类型不匹配.Required: Boolean, found: Future[Boolean] in scala.<



大家好,我是Scala的新手。我在我的代码中有一个if/else条件,它将通过布尔变量(这是一个未来)检查一些东西,但它说"类型不匹配。Required: Boolean, found: Future[Boolean]"我怎样才能让它工作?

autoCondition      = configRepository.getAutoCondition //Future[Boolean] variable.
.
. //some other stuff here
.
yield if (autoCondition) page else autoPage

autoConditionFuture[Boolean]。使用这种值的通常方法是对其进行映射。

autoCondition.map(if (_) page else autoPage)
// short for:
autoCondition.map(x => if (x) page else autoPage)

但是你的问题中的代码不完整。你似乎已经开始理解了。如果for-comprehension超过了Future,您可能只需要像这样更改代码

for {
// other stuff ...
autoCondition <- configRepository.getAutoCondition
// other stuff ...
} yield if (autoCondition) page else autoPage

如果你在for-comprehension中使用<-,那么代码将被转换为一系列mapflatMap调用。

看起来你正在使用scala的未来(也许你正在连接到db或类似的东西你可以做两件事中的一件

1:映射未来。这就意味着你的代码看起来像这样

configRepository.getAutoCondition.map{
condition =>
if(condition) page else autoPage
}

注意:这也将返回你的页面/autoPage返回的任何数据类型的Future

2:你可以使用Await。这将等待x间隔时间的结果,并返回布尔值。你的代码看起来像这样

import scala.concurrent._
import scala.concurrent.duration._
val conditionVariable=Await.result(configRepository.getAutoCondition, 100 nanos)
if(conditionVariable) page else autoPage

第二个变量是等待的时间

Ps:第二个方法将使你的函数调用同步。所以从技术上讲,这是不推荐的。然而,看看你的代码,似乎你正在做一个页面调用。明智地使用其中之一

最新更新