簡體   English   中英

是否可以在Scala中指定匿名函數的返回類型?

[英]Is it possible to specify an anonymous function's return type, in Scala?

我知道你可以創建一個匿名函數,讓編譯器推斷它的返回類型:

val x = () => { System.currentTimeMillis }

僅為了靜態類型,是否可以指定其返回類型? 我認為這會讓事情變得更加清晰。

val x = () => { System.currentTimeMillis } : Long

在我看來,如果你想讓事情變得更清楚,最好通過在那里添加類型注釋而不是函數的結果來記錄對標識符x的期望。

val x: () => Long = () => System.currentTimeMillis

然后編譯器將確保右側的函數滿足該期望。

法比安給出了直截了當的方式,但如果你喜歡微觀管理糖,其他一些方法包括:

val x = new (() => Long) {
  def apply() = System.currentTimeMillis
}

要么

val x = new Function0[Long] {
  def apply() = System.currentTimeMillis
}

甚至

val x = new {
  def apply(): Long = System.currentTimeMillis
}

因為在大多數情況下,如果它從Function下降,只有它是否有一個應用,它沒有任何區別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM