Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern match with varargs

Tags:

scala

I've a web server to handle incoming requests. Based on the http method and endpoint I process requests differently. Currently the code handles it:

def routes: HttpRequest => Future[HttpResponse] = { httpRequest: HttpRequest =>
    (httpRequest.method, httpRequest.uri.path.toString) match {
      case (GET, "/login") =>
         process(getLogin)

      case (POST, "/newUser") =>
        process(createNewUser)   

      ..

But now I need to support a bunch of related endpoints of this form:

/{version}/{serviceName}

For example:

/0/userService
/0/bookService

So I want to update existing code to support the new endpoints:

case (POST, "/${version}/${service}) => 
        if ($version == 0 && $service.equalToIgnoreCase("userService")) 
            process(user service)       

        if ($version == 0 && $service.equalToIgnoreCase("bookService"))     
            process(book service)

How can I do that?

like image 716
user468587 Avatar asked Feb 27 '26 21:02

user468587


1 Answers

You could do something like this:

val UrlPattern: scala.util.matching.Regex = """/(.*)/(.*)""".r
val path = "/0/userService"  

path match {
    case UrlPattern(version, service) => println(version, version)
}

The code above will result in:

(0, userService)

being printed to the console, but you can to whatever you want with the variables.

like image 79
senjin.hajrulahovic Avatar answered Mar 01 '26 19:03

senjin.hajrulahovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!