I have the following code:
def authenticateByUsername(username: String, password:String): Boolean = {
val user = users.findOne(MongoDBObject(USERNAME -> username))
if(user.isDefined){
val pw = user.get.getAs(PASSWORD)
if(pw.isDefined)
BCrypt.checkpw(pw.get, password)
else false
}else false
}
Is there a more idiomatic way of doing this? It’s an if-else nightmare, which just doesn’t seem right in Scala.
You’re correct that there’s a better way, and in general using
get(or, to a slightly lesser degree,isDefined) on anOptionis a red flag. In this case you can use afor-comprehension:Or, a little more concisely:
The latter is essentially just a desugared version of the
for-comprehension.