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
That way, the type of
Noneis set toNone.typeand the variablenameis inferred to be of typeNothing. (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 methodname.trimexists and it won’t compile.If you had
request.getParameter("name")available, its type would beOption[String],namewould potentially have typeStringandname.trimwould compile.You can work around this by specifying the type of
None: