Skip to content

理解 Either 和 Option #11

@zhongl

Description

@zhongl

这儿有道题, 从实际的项目中简化而来:

case class User(id: Long, nickname: String, password: String, mobile: String)

object Users {
  def userBy(mobile: String): Option[User] = 
    if (mobile == "01234567890") Some(User(1L, "allen", "******", "01234567890")) else None

  def authenticate(mobile: String, password: String): Either[User, String] = ???
}

assert(Users.authenticate("allen", "******") == Right("Invalid mobile"))
assert(Users.authenticate("01234567891", "******") == Right("Mobile not found"))
assert(Users.authenticate("01234567890", "??????") == Right("Invalid password"))
assert(Users.authenticate("01234567890", "******") == Left(User(1L, "allen", "******", "01234567890")))

请根据assert提示实现authenticate.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions