Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option monad in scala

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?

like image 450
ryskajakub Avatar asked Nov 26 '10 19:11

ryskajakub


1 Answers

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]
like image 95
Debilski Avatar answered Oct 04 '22 06:10

Debilski