亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Scala中的方法參數驗證,用于理解和單子

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) )    }  }
查看完整描述

3 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

我完全支持Ben James的建議,為產生null的api做包裝。但是編寫該包裝器時仍然會遇到相同的問題。所以這是我的建議。


為什么單子為什么要理解?IMO過于復雜。這是您可以執行的操作:


def buildNormalCategory

  ( user: User, parent: Category, name: String, description: String )

  : Either[ Error, Category ] 

  = Either.cond( 

      !Seq(user, parent, name, description).contains(null), 

      buildTrashCategory(user),

      Error(Error.FORBIDDEN, "null detected")

    )

或者,如果您堅持讓錯誤消息存儲參數名稱,則可以執行以下操作,這將需要更多樣板:


def buildNormalCategory

  ( user: User, parent: Category, name: String, description: String )

  : Either[ Error, Category ] 

  = {

    val nullParams

      = Seq("user" -> user, "parent" -> parent, 

            "name" -> name, "description" -> description)

          .collect{ case (n, null) => n }


    Either.cond( 

      nullParams.isEmpty, 

      buildTrashCategory(user),

      Error(

        Error.FORBIDDEN, 

        "Null provided for the following parameters: " + 

        nullParams.mkString(", ")

      )

    )

  }


查看完整回答
反對 回復 2019-10-08
  • 3 回答
  • 0 關注
  • 816 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號