大家好,我是Scala的新手。我的代碼中有一個if/else條件,它將通過一個布爾變數(這是一個未來變數)來檢查一些東西,但它顯示 "型別不匹配。需要。布爾型,發現。Future[Boolean]"。我怎樣才能讓它作業呢?
autoCondition = configRepository.getAutoCondition /Future[Boolean] variable.
.
. //Some other stuff here .
.
yield if (autoCondition) page else autoPage
uj5u.com熱心網友回復:
autoCondition是一個Future[Boolean]。使用這樣一個值的通常方法是對它進行映射。
autoCondition.map(if (_) page else autoPage)
// short for:
autoCondition.map(x => if (x) page else autoPage)
但是你問題中的代碼并不完整。你似乎已經在使用一個for-comprehension。如果這個for-comprehension是在Future之上,你可能只需要像這樣修改你的代碼
for {
//其他東西 ...
autoCondition <- configRepository.getAutoCondition
//其他東西 ... autoCondition <- configRepository.getAutoCondition
} yield if (autoCondition) page else autoPage
如果你在for-comprehension里面使用<-,該代碼將被翻譯成一系列的map和flatMap呼叫。
uj5u.com熱心網友回復:
看起來你在使用scala future(也許你正在連接到資料庫或類似的東西) 你可以做兩件事中的一件
1:對未來進行映射。這意味著你的代碼會是這樣的1:映射未來。
configRepository.getAutoCondition.map{
condition =>
if(condition) page else autoPage
}
注意。這也將回傳你的page/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: 第二種方法會使你的函式被同步呼叫。所以從技術上講,不建議使用這種方法。但是看你的代碼,你似乎在做一個頁面呼叫。在這兩種方法中明智地使用一種吧
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/309098.html
標籤:
