2013-03-04 52 views
3
details.bindFromRequest.fold(
    errors => BadRequest(views.html.adminpages.aboutusimgsForm(errors)), 

[NoSuchElementException: None.get]錯誤的形式錯過比賽型

從這個表格

@(details: Form[AboutImages]) 

<input type="hidden" name="id" value="@details.get.id"> 
<input type="text" name="name" value="@details.get.name"> 

我有一個從數據庫(MySQL的)添加文本和隱藏的表單輸入編輯表單aboutusimgs/edit/1

但是,當我不填寫表格和綁定的錯誤部分執行:

errors => BadRequest(views.html.adminpages.aboutusimgsForm(errors)),

我得到NoSuchElementException我必須做的另一種形式只是錯誤爲什麼我只是用編輯表單?

感謝

+0

你通過訪問形式'value.get'直接在你的模板? – 2013-03-04 09:20:05

回答

1

這裏的問題是,如果一個未設置值,它將有None的價值。 None.get總是拋出一個NoSuchElementException,因爲它顯然沒有元素。您可以通過多種方式處理Option,但如果您有默認設置,則可以簡單地使用getOrElse。 E.g:

// first map it to the id, then get the value or default if None 
details.map(_.id).getOrElse("") 

你也應該有一個看的scala docsOption型和閱讀一個或兩個有關如何使用選項的幾篇文章。

0

要與Option的結果一起工作,您不應該直接使用get方法。

爲什麼?因爲它完全導致潛在的NullPointerException來自Java的概念(因爲拋出NoSuchElementException爲None)=>以您的編碼方式防止安全。

要檢索的結果,尤其是做根據檢索到的有價值的東西,喜歡圖案匹配越好,越短fold方法:

/** Returns the result of applying $f to this $option's 
    * value if the $option is nonempty. Otherwise, evaluates 
    * expression `ifEmpty`. 
    * 
    * @note This is equivalent to `$option map f getOrElse ifEmpty`. 
    * 
    * @param ifEmpty the expression to evaluate if empty. 
    * @param f  the function to apply if nonempty. 
    */ 
    @inline final def fold[B](ifEmpty: => B)(f: A => B): B = 
    if (isEmpty) ifEmpty else f(this.get) 

或者,你可以選擇使用getOrElse方法,如果您只想檢索在Option的結果,並提供一個默認值,如果你對付一個None

/** Returns the option's value if the option is nonempty, otherwise 
    * return the result of evaluating `default`. 
    * 
    * @param default the default expression. 
    */ 
    @inline final def getOrElse[B >: A](default: => B): B = 
    if (isEmpty) default else this.get 
0

假設你有一個List[Option[String]]Seq ...該解決方案是使用flatMap從而消除None這樣

List(Some("Message"),None).map{ _.get.split(" ") } //throws error 

但如果你使用flatmap

List(Some("Message"),None).flatMap{ i => i }.map{ _.split(" ") } //Executes without errors