Check if a string is blank or doesn't exist in Scala

前端 未结 9 1371
误落风尘
误落风尘 2021-02-01 16:29

I have an Option[String].

I want to check if there is a string exists and if it\'s exists its not blank.

def isBlank( input : Option[Strin         


        
9条回答
  •  情书的邮戳
    2021-02-01 17:12

    You can also take advantage of Extractor pattern. It makes codes much more declarative.

    For example:

    object NonBlank {
      def unapply(s: String): Option[String] = Option(s).filter(_.trim.nonEmpty) 
    }
    

    And then use it like

    def createUser(name: String): Either[Error, User] = name match {
      case NonBlank(username) => Right(userService.create(username))
      case _ => Left(new Error("Invalid username. Blank usernames are not allowed."))
    }
    

提交回复
热议问题