2014-03-06 39 views
10

我試圖定義一個可選的查詢參數將映射到一個Long,但會null當它不存在的網址: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可選查詢參數的默認值?什麼是替代方式來做到這一點?

回答

23

請記住,路由中的可選查詢參數類型爲scala.Long,而不是java.lang.Long。 Scala的Long類型相當於Java的基本原型long,無法賦值爲null

更改idjava.lang.Long類型應該可以解決編譯錯誤,並且也許是解決問題的最簡單的方法:

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

您也可以嘗試在斯卡拉Option包裝id,看到這是在Scala中處理可選值的推薦方式。但是我不認爲Play會將可選的Scala Long映射到可選的Java Long(反之亦然)。你要麼必須在你的路線Java類型:在Java代碼中

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

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

或者Scala的類型:

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

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

hey @avik ...該方法聲明對於這個'Option [Long]'東西是什麼樣的...? – Hristo

+0

@Hristo - 我已經更新並充實了我的答案。 – avik

1

在我來說,我使用一個字符串變量。

例子:

在我的路線:

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

然後,我在我的代碼轉換與解析器龍 - >的Long.parseLong。

但我同意Hristo的方法是最好的。