java - 为路由中的可选查询参数分配空默认值 - Play Framework

标签 java routes playframework-2.0

我正在尝试定义一个可选的查询参数,它将映射到一个 Long,但当它不在 URL 中时将为 null:

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

...我基本上想检查它是否被传入:

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

但是,我遇到了一个编译错误:

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 可选查询参数的默认值?执行此操作的替代方法是什么?

最佳答案

请记住,路由中的可选查询参数是 scala.Long 类型,而不是 java.lang.Long。 Scala 的 Long 类型等同于 Java 的原始 long,不能赋值为 null

id 更改为 java.lang.Long 类型应该可以修复编译错误,这也许是解决问题的最简单方法:

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

您也可以尝试将 id 包装在 Scala Option 中,因为这是 Scala 中处理可选值的推荐方式。但是我认为 Play 不会将可选的 Scala Long 映射到可选的 Java Long(反之亦然)。你要么必须在你的 route 有一个 Java 类型:

GET  /foo  controller.Foo.index(id: Option[java.lang.Long])

public static Result index(final Option<Long> id) {
    if (!id.isDefined()) {...}
    ...
}

或者 Java 代码中的 Scala 类型:

GET  /foo  controller.Foo.index(id: Option[Long])

public static Result index(final Option<scala.Long> id) {
    if (!id.isDefined()) {...}
    ...
}

关于java - 为路由中的可选查询参数分配空默认值 - Play Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22234140/

相关文章:

java - 如何以编程方式更改 RecyclerView 项目属性,特别是 recyclerview 项目内的自定义 View

java - Android更改recyclerview中所有项目中的textview而不重绘整个列表

java - 如何修复 "HTTP Status 500- Servlet exception threw an exception"

CakePHP 2.x 反向路由链接助手

java - 为什么java说我还没有初始化变量?

asp.net-core - ASP.NET Core 6 razor页面路由不同区域内的默认页面路由

快速路由 : multiple URLs to the same route

html - Scala 字符串集合——一种输出不带双引号的字符串的方法

java - 如何根据用户是否登录来查看或隐藏某些数据?

java - 将 api 添加到 Play Framework 中 URL 的根目录前