Reputation: 85
details.bindFromRequest.fold(
errors => BadRequest(views.html.adminpages.aboutusimgsForm(errors)),
[NoSuchElementException: None.get]
From this form
@(details: Form[AboutImages])
<input type="hidden" name="id" value="@details.get.id">
<input type="text" name="name" value="@details.get.name">
I have an edit form aboutusimgs/edit/1
that adds text and hidden form inputs from the databases(mysql).
But when I don't fill in the form and the error part of the bind executes:
errors => BadRequest(views.html.adminpages.aboutusimgsForm(errors)),
I get the NoSuchElementException
do I have make another form just for errors why can I just use the edit form?
Thanks
Upvotes: 3
Views: 570
Reputation: 955
Assuming you have a List[Option[String]]
or Seq
... the solution would be to use flatMap
which removes None
so
List(Some("Message"),None).map{ _.get.split(" ") } //throws error
but if you use flatmap
List(Some("Message"),None).flatMap{ i => i }.map{ _.split(" ") } //Executes without errors
Upvotes: 0
Reputation: 22191
To work with Option
's results, you should never ever use get
method directly.
Why? Because it leads exactly to a potential NullPointerException concept from Java (since throwing NoSuchElementException by None
) => preventing safety in your way of coding.
To retrieve result and especially do something according to the retrieved value, prefer pattern matching or better, the shorter fold
method:
/** 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)
Alternatively, you can choose to use getOrElse
method if you only want to retrieve the Option
's result and provide a default value if you deal with a 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
Upvotes: 0
Reputation: 24403
The problem here is, that if a value is not set, it will have None
as value. None.get
always throws a NoSuchElementException
, because it obviously has no element. You can handle Option
s in several ways, but if you have a default, you can simply use getOrElse
. E.g:
// first map it to the id, then get the value or default if None
details.map(_.id).getOrElse("")
You should also have a look at the the scala docs for the Option
type and read one or two of the several articles about how to use options.
Upvotes: 1