how is meant to work Option monad? I'm browsing the scala api and there is an example (I mean the second one),
Because of how for comprehension works, if None is returned from request.getParameter, the entire expression results in None
But when I try this code:
val upper = for {
name <- None //request.getParameter("name")
trimmed <- Some(name.trim)
upper <- Some(trimmed.toUpperCase) if trimmed.length != 0
} yield upper
println(upper.getOrElse(""))
I get a compile error. How is this supposed to work?
You get a compiler error because of this
name <- None
That way, the type of None
is set to None.type
and the variable name
is inferred to be of type Nothing
. (That is, it would have this type if it actually existed but obviously the for comprehension does not even get to creating it at runtime.) Therefore no method name.trim
exists and it won’t compile.
If you had request.getParameter("name")
available, its type would be Option[String]
, name
would potentially have type String
and name.trim
would compile.
You can work around this by specifying the type of None
:
name <- None: Option[String]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With