猿问

Scala中的方法参数验证,用于理解和单子

我正在尝试验证方法的参数是否为空,但找不到解决方案...


有人可以告诉我该怎么做吗?


我正在尝试这样的事情:


  def buildNormalCategory(user: User, parent: Category, name: String, description: String): Either[Error,Category] = {

    val errors: Option[String] = for {

      _ <- Option(user).toRight("User is mandatory for a normal category").right

      _ <- Option(parent).toRight("Parent category is mandatory for a normal category").right

      _ <- Option(name).toRight("Name is mandatory for a normal category").right

      errors : Option[String] <- Option(description).toRight("Description is mandatory for a normal category").left.toOption

    } yield errors

    errors match {

      case Some(errorString) => Left( Error(Error.FORBIDDEN,errorString) )

      case None =>  Right( buildTrashCategory(user) )

    }

  }


料青山看我应如是
浏览 785回答 3
3回答

largeQ

我完全支持Ben James的建议,为产生null的api做包装。但是编写该包装器时仍然会遇到相同的问题。所以这是我的建议。为什么单子为什么要理解?IMO过于复杂。这是您可以执行的操作:def buildNormalCategory&nbsp; ( user: User, parent: Category, name: String, description: String )&nbsp; : Either[ Error, Category ]&nbsp;&nbsp; = Either.cond(&nbsp;&nbsp; &nbsp; &nbsp; !Seq(user, parent, name, description).contains(null),&nbsp;&nbsp; &nbsp; &nbsp; buildTrashCategory(user),&nbsp; &nbsp; &nbsp; Error(Error.FORBIDDEN, "null detected")&nbsp; &nbsp; )或者,如果您坚持让错误消息存储参数名称,则可以执行以下操作,这将需要更多样板:def buildNormalCategory&nbsp; ( user: User, parent: Category, name: String, description: String )&nbsp; : Either[ Error, Category ]&nbsp;&nbsp; = {&nbsp; &nbsp; val nullParams&nbsp; &nbsp; &nbsp; = Seq("user" -> user, "parent" -> parent,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "name" -> name, "description" -> description)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect{ case (n, null) => n }&nbsp; &nbsp; Either.cond(&nbsp;&nbsp; &nbsp; &nbsp; nullParams.isEmpty,&nbsp;&nbsp; &nbsp; &nbsp; buildTrashCategory(user),&nbsp; &nbsp; &nbsp; Error(&nbsp; &nbsp; &nbsp; &nbsp; Error.FORBIDDEN,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; "Null provided for the following parameters: " +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; nullParams.mkString(", ")&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; )&nbsp; }
随时随地看视频慕课网APP
我要回答