assign null default value for optional query param in route - Play Framework

前端 未结 2 1962
情深已故
情深已故 2021-01-04 12:53

I\'m trying to define an optional query parameter that will map to a Long, but will be null when it is not present in the URL:

GET          


        
相关标签:
2条回答
  • 2021-01-04 13:24

    In my case I use a String variable.

    Example :

    In my route :

    GET /foo controller.Foo.index(id: String ?= "")

    Then I convert in my code with a parser to Long --> Long.parseLong.

    But I agree that the method of Hristo is the best.

    0 讨论(0)
  • 2021-01-04 13:33

    Remember that the optional query parameter in your route is of type scala.Long, not java.lang.Long. Scala's Long type is equivalent to Java's primitive long, and cannot be assigned a value of null.

    Changing id to be of type java.lang.Long should fix the compilation error, and is perhaps the simplest way to resolve your issue:

    GET  /foo  controller.Foo.index(id: java.lang.Long ?= null)
    

    You could also try wrapping id in a Scala Option, seeing as this is the recommended way in Scala of handling optional values. However I don't think that Play will map an optional Scala Long to an optional Java Long (or vice versa). You'll either have to have a Java type in your route:

    GET  /foo  controller.Foo.index(id: Option[java.lang.Long])
    
    public static Result index(final Option<Long> id) {
        if (!id.isDefined()) {...}
        ...
    }
    

    Or a Scala type in your Java code:

    GET  /foo  controller.Foo.index(id: Option[Long])
    
    public static Result index(final Option<scala.Long> id) {
        if (!id.isDefined()) {...}
        ...
    }
    
    0 讨论(0)
提交回复
热议问题