Of course, I can only guess what you really want to achieve, but I assume that you simply do not want to map specific URLs, and also extract information from the given strings. For example. when specifying "/foo/21" you just don't want to know that this matches some "foo" / 21 , but you want to do something with a value of 21.
Ive found that the URI matching process in Lift is very useful, so maybe this is suitable for your use case. (Of course, I am using a very simplified version). It is made using lists, which simplifies matching, but it also means that you need to use :: instead of / .
But this is not the main thing: what I want to show is the advantage of using implicit transformations and extractor power
object AsInt { def unapply(i: String): Option[Int] = try { Some(i.toInt) } catch { case e: java.lang.NumberFormatException => None } } def matchUrl(url: String) = { val req:List[String] = url.split('/').toList.drop(1) req match { case "foo" :: "bar" :: Nil => println("bar") case "foo" :: AsInt(i) :: Nil => println("The square is " + i*i) case "foo" :: s :: Nil => println("No int") case _ => println("fail") } } matchUrl("/foo/21") matchUrl("/foo/b") matchUrl("/foo/bar") matchUrl("/foobar")
In short, using an AsInt extractor instead of implicitly converting Int to String , you can actually extract an integer value from a string if and only if it is convertible and, of course, use it immediately. Obviously, if you don't like the naming convention, you can change it to something more unobtrusive, but if you really want to perform URL mapping, you probably shouldn't completely convert everything.
Debilski
source share