Routing overloaded functions in Play Framework 2.0

java, playframework, playframework-2.0

Solution

No, it's not possible, there are two solutions.

First is to use 2 names:

public static Result getByLong(Long id) {
    return ok("Long value: " + id);
}

public static Result getByString(String name) {
    return ok("String value: " + name);
}

also you should use separate routes for it, otherwise you'll get type mismatch

GET   /p-by-long/:id         controllers.Monitor.getByLong(id: Long)
GET   /p-by-string/:name     controllers.Monitor.getByString(name: String)

Second solution is using one method with String argument and check internally if it can be converted to Long

public static Result getByArgOfAnyType(String arg) {
    try {
        Long.parseLong(arg);
        return ok("Long: " + arg);
    } catch (Exception e) {
        return ok("String: " + arg);
    }
}

route:

GET   /p/:arg     controllers.Monitor.getByArgOfAnyType(arg : String)

I know that doesn't fit your question but at least will save your time. Also keep in mind that there could be better ways to determine if String can be converted to numeric type, ie in this question: What's the best way to check to see if a String represents an integer in Java?

Problem

In Play, when overloading controller methods, those individual methods cant be routed more than once cause the complier doesn't like it. Is there a possible way to get around this? Say if I had two functions in my `Product` controller: `getBy(String name)` and `getBy(long id)`. And I had two different routes for these functions declared in `routes`: ``` GET /p/:id controllers.Product.getBy(id: Long) GET /p/:name controllers.Product.getBy(name: String) ``` I want to use the "same" function for different routes, is this possible?

Original source

Related problems