2 回答

TA貢獻1963條經(jīng)驗 獲得超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`
? }?
}
保證返回完全相同的數(shù)組的就地排序(這里并沒有真正排序任何東西):
def sortInPlace[A: Ordered](arr: Array[A]): arr.type = {
? /* do fancy stuff with indices etc. */
? arr
}
如果您嘗試返回不同的數(shù)組,
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)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^
這稱為單例類型,并在規(guī)范中進行了解釋。

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