Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Type Mismatch

I am having a problem with type mismatch.

type mismatch; found : Option[models.User] required: models.User

def authenticate = Action { implicit request =>
        signinForm.bindFromRequest.fold(
          formWithErrors => BadRequest(html.signin(formWithErrors)),
          user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user))
        )
      }

How can I force the function to accept Option[models.User] or can I convert the models.User into an Option?

The error occurs here: User.getUserName(user). getUserName requires models.User types.

===============================================

Update with all code used:

From User.scala

  def authenticate(email: String, password: String) : Option[User] = {
    (findByEmail(email)).filter { (user => BCrypt.checkpw(password, user.password)) }
  }

  def findByEmail(email: String) : Option[User] = {
    UserDAO.findOne(MongoDBObject("email" -> email))
  }

From Application.scala

  val signinForm = Form {
    mapping(
      "email" -> nonEmptyText, 
      "password" -> text)(User.authenticate)(_.map(user => (user.email, "")))
      .verifying("Invalid email or password", result => result.isDefined)
  }

  def authenticate = Action { implicit request =>
    signinForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.signin(formWithErrors)),
      user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user.get))
    )
  }
like image 263
DrWolfe Avatar asked Apr 02 '26 02:04

DrWolfe


1 Answers

To de-option an Option[User] into a User, you can do one of the following:

1) The unsafe way. Only do this if you are sure that optUser is not None.

val optUser: Option[User] = ...
val user: User = optUser.get

2) The safe way

val optUser: Option[User] = ...
optUser match {
  case Some(user) => // do something with user
  case None => // do something to handle the absent user
}

3) The monadic safe way

val optUser: Option[User] = ...
optUser.map(user => doSomething(user))

The biggest thing is that, if it's possible that optUser might actually be None, you need to figure out what you actually want to happen in the case that there is no User object.

There's a lot more information about Option in other StackOverflow questions if you'd like to read more.

like image 130
dhg Avatar answered Apr 08 '26 15:04

dhg