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

两盒软妹~` 提交于 2019-12-18 19:31:15

问题


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  /foo  controller.Foo.index(id: Long ?= null)

... and I essentially want to check if it was passed in or not:

public static Result index(Long id) {
    if (id == null) {...}
    ...
}

However, I'm getting a compilation error:

type mismatch; found : Null(null) required: Long Note that implicit conversions are not applicable because they are ambiguous: both method Long2longNullConflict in class LowPriorityImplicits of type (x: Null)Long and method Long2long in object Predef of type (x: Long)Long are possible conversion functions from Null(null) to Long

Why can't I do this, assigning null to be a default value for an expected Long optional query parameter? What's an alternative way to do this?


回答1:


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()) {...}
    ...
}



回答2:


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.



来源:https://stackoverflow.com/questions/22234140/assign-null-default-value-for-optional-query-param-in-route-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!