为路由中的可选查询参数指定null默认值 - Play Framework [英] assign null default value for optional query param in route - Play Framework
问题描述
我正在尝试定义一个可选的查询参数,该参数将映射到 Long
,但是 null
当它不在URL中时:
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:
类型不匹配; found:Null(null)required:Long请注意,隐式
转换不适用,因为它们不明确:两个方法
类LowPriorityImplicits中的Long2longNullConflict类型(x:
Null)Long和方法Long2long in object Predef of type(x:Long)Long
是可能的转换函数,从Null(null)到Long
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
为什么我不能这样做,将 null
指定为预期 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?
推荐答案
请记住路线中的可选查询参数类型为 scala.Long
,而不是 java.lang.Long
。 Scala的Long类型相当于Java的原始 long
,并且不能赋值为 null
。
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
.
将 id
更改为 java.lang.Long
类型应修复编译错误,也许是解决问题的最简单方法:
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)
你也可以尝试包装 id
在Scala 选项
中,因为这是Scala处理可选值的推荐方法。但是我不认为Play会将可选的Scala Long映射到可选的Java Long(反之亦然)。您要么必须在路线中使用Java类型:
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()) {...}
...
}
或Java代码中的Scala类型:
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()) {...}
...
}
这篇关于为路由中的可选查询参数指定null默认值 - Play Framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!