Home > Enterprise >  Type mismatch. Required: Boolean, found: Future[Boolean] in scala
Type mismatch. Required: Boolean, found: Future[Boolean] in scala

Time:09-17

Hello everyone I'm new to Scala. I have an if/else condition in my code which will check something by a Boolean variable (which is a future) but it says "Type mismatch. Required: Boolean, found: Future[Boolean]". How can I make it work?

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

CodePudding user response:

autoCondition is a Future[Boolean]. The usual way to use such a value is to map over it.

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

But the code in your question is not complete. You already seem to be working with a for-comprehension. If that for-comprehension is over Future, you probably only have to change your code like this

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

If you use <- inside a for-comprehension that code will be translated to a series of map and flatMap calls.

CodePudding user response:

Looks like you are using scala future(Maybe you are connecting to db or something like that You could do one among 2 things

1: Map over the future. Which would mean your code would look something like this

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

Beware: This is also going to return Future of whatever datatype your page/autoPage returns

2: You could use a Await. This would wait for the result for x interval of time and would return you the boolean. Your code would look something like this

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

where the second variable is the amount of time you would wait

Ps: 2nd method would make your function call synchronous. So technically it isnt recommended. However looking at your code it seems like you are doing a page call. Use one among these 2 wisely

  • Related