[2.0.4 scala] any less verbose way to extract params ?

66 views
Skip to first unread message

Arun Ramakrishnan

unread,
Oct 25, 2012, 3:30:53 PM10/25/12
to play-fr...@googlegroups.com
I am just trying to extract a numeric paging limit. But, this seems unnecessarily verbose to me. Not to mention there is relatively some sophisticated syntax here.

  
  val limit = request.queryString.get("limit").flatMap{
      import scala.util.control.Exception._;
      catching(classOf[NumberFormatException]) opt _(0).toInt
    }.getOrElse(10)


Some thoughts on what I would like it to look like.

val limit = request.getFirstParam("limit").parseOptionInt.getOrElse(10).

Of course, I could write a some implicit or utility code to do just that. But, every time i am doing a quick prototype of an app, that would be cumbersome to maintain and carry around.

thanks
Arun

peter hausel

unread,
Oct 25, 2012, 3:53:54 PM10/25/12
to play-fr...@googlegroups.com
what's wrong with using a simple function?

scala> def parseToInt(s: Option[String]): Int = {
     |  val intCatch = util.control.Exception.catching(classOf[NumberFormatException]).withApply(_ => 0)
     |  s.map(s => intCatch(s.toInt)).getOrElse(0)
     | }
parseToInt: (s: Option[String])Int

scala> parseToInt(Some("1"))
res0: Int = 1

scala> parseToInt(Some("sdf"))
res1: Int = 0

scala> parseToInt(None)
res2: Int = 0

in your case: 

parseToInt(request.queryString.get("limit"))

Julien Richard-Foy

unread,
Oct 25, 2012, 4:04:56 PM10/25/12
to play-fr...@googlegroups.com
Why don’t you catch this parameter from your route definition?

GET /list controllers.App.list(p: Option[Int])

Arun Ramakrishnan

unread,
Oct 25, 2012, 5:05:46 PM10/25/12
to play-fr...@googlegroups.com
Thanks guys. 

Julien, good tip. didn't know about it.

Peter, The fact that one has to write a utility method. Its too much work for a common task such as this.  And I had to lookup what "withApply" does. YMMV :-)

thanks
Arun 

On Thu, Oct 25, 2012 at 1:04 PM, Julien Richard-Foy <j...@zenexity.com> wrote:
Why don’t you catch this parameter from your route definition?

GET  /list    controllers.App.list(p: Option[Int])

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To post to this group, send email to play-fr...@googlegroups.com.
To unsubscribe from this group, send email to play-framewor...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/play-framework?hl=en.


Reply all
Reply to author
Forward
0 new messages