I have some code written in Lift. Basically its nested Box (similar monad to Option). I'd like to simplify it a little bit if possible. Preferably add type parameter so this could be easily changed to string or double if needed. Here is the code
tryo(r.param("boolean parameter").map(_.toBoolean)).map(_.openOr(false)).openOr(false)
"tryo" is helper function to catch and wrap results in Box if exception occurs and r is Req object. "param" function returns Box[String] (that comes from request param). I'd like to make it working for Int's String's etc. and if possible get rid of nested map/openOr (getOrElse in you think in Option types).
Monad transformers ?
My little bit tweaked version building on @pr1001 and @paradigmatic ground.
And usage in my case:
If you want to absract the type, you need to abstract both the default value, and the conversion from a string:
Then define implicit instances for your types:
Finally, use pr1001 answer, using an implicitly provided value of converter:
The compiler will select the appropriate converter instance for you:
flatMap
that sh*t!Or, use a for comprehension:
But that doesn't solve your ability to get different types. For that I would suggest something like:
This is untested... Note also that
scala.util.control.Exception.allCatch.opt()
will return anOption
just liketryo
returns aBox
.