Search code examples
scalaswitch-statementpattern-matching

How to remove pattern matching for verifying user information in scala?


I am new to Scala as have been java developer until now.

I have a functionality to login like where user can have multiple passwords:

def login(User user) : Boolean = {
 String username = user.username
 String password = user.password

 (username, password) match {
   case("Amit","AmitSecret1" | "AmitSecret2") => true
   case("Rahul","Atemporary") => true
   case("Tom","Howareyou") => true
   case("Roger","Dummy") => true
   ...
   ... // lot of other cases
   case("_","_") => false
 }

}

Is there any other way of verifying login check without pattern matching which does not involves case for every combination?


Solution

  • You could have a Map[Username, Set[Password]] you could then do:

    def login(user: User): UserStatus = {
      map.get(key = user.username).fold(ifEmpty = UserDoesNotExist) { passwords =>
        if (passwords.contains(user.password))
          AuthenticatedUser
        else
          BadPassword
      }
    

    I just made up the whole UserStatus ADT, but I hope the intent is clear.