Jeff Lee Jeff Lee -4 years ago 250
Scala Question

scala for comprehension condition operation

In my scala program, I have few operation in for-comprehension. I want to have a if condition inside like this,

user <- userDao.findUser(authToken)
haveDevice <- userDao.haveDevice(deviceId, deviceType)
if (haveDevice) {
r <- userDao.addDevice(user.id, deviceId, deviceType)
}


But above code is invalid, how to do this? Thanks

Answer Source

proper syntax for using if condition inside a for comprehension is as shown below.

for {
  user <- userDao.findUser(authToken)
  haveDevice <- userDao.haveDevice(deviceId, deviceType)
  r <- userDao.addDevice(user.id, deviceId, deviceType) if haveDevice
}

assuming your for comprehension operates on a Future, if the if condition fails then the entire comprehension returns a failed Future with error

java.util.NoSuchElementException: Future.filter predicate is not satisfied

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download