2 回答

TA貢獻1963條經驗 獲得超6個贊
你可以 - 在 Scala 中。
類的方法返回this.type:
class C {
? var x = 0?
? /** Sets `x` to new value `i`, returns the same instance. */
? def with_x(i: Int): this.type = {
? ? x = i
? ? this? ?// must be `this`, can't be arbitrary `C`
? }?
}
保證返回完全相同的數組的就地排序(這里并沒有真正排序任何東西):
def sortInPlace[A: Ordered](arr: Array[A]): arr.type = {
? /* do fancy stuff with indices etc. */
? arr
}
如果您嘗試返回不同的數組,
def badSortInPlace(arr: Array[Int]): arr.type = Array(1, 2, 3) // won't compile
你會在編譯時得到一個錯誤:
error: type mismatch;
found? ?: Array[Int]
required: arr.type
? ? ? def badSortInPlace(arr: Array[Int]): arr.type = Array(1, 2, 3)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^
這稱為單例類型,并在規范中進行了解釋。

TA貢獻1848條經驗 獲得超2個贊
在具有參數多態性的語言中,任何類型的函數
a → a
必須是恒等函數:因為該函數在 中是多態的a
,所以它不可能知道關于 的任何信息a
,特別是它不可能知道如何構造一個a
. 由于它也不采用世界值或IO
monad 或等價物,因此它無法從全局狀態、數據庫、網絡、存儲或終端獲取值。它也不能刪除該值,因為它必須返回一個a
.
因此,它唯一能做的就是返回a
傳入的內容。
- 2 回答
- 0 關注
- 152 瀏覽
添加回答
舉報