CDuce/Types/Coercion
外觀
let x = 7;; -> val x : 7 = 7
x 的值為 7,型別為 7(包含整數七的單例)
let y1 = (x : Int);; let y2 : Int = x;;
這兩個向上強制轉換的結果相同:值為 7,型別為 Int。這是可能的,因為單例 7 是整數集的子集。
靜態向下強制轉換不可行
type Positive = 1--* let y = (7 : Int);;
let yp = (y : Positive);; -> This expression should have type: Positive but its inferred type is: Int which is not a subtype, as shown by the sample: *--0
但動態向下強制轉換可行
let yp1 :? Positive = y;; let yp2 = (y :? Positive);;
如果強制轉換不可行,則在執行時會引發一個異常
let ybad = (y :? Char);; -> Uncaught CDuce exception: "Value 7 does not match type Empty\n"
訊息中包含 "Empty" 是因為動態強制轉換會給出合取型別。這可以透過以下方式看到
(7 : 1--8) :? 5--10;;
它看起來具有型別 5--8
請注意,對於向上強制轉換,靜態方法效率更高,並且提供更好的錯誤處理。此外,由於合取機制,向上強制轉換不能是動態的
(7 : 1--8) :? Int;;
仍然是型別 1--8,而不是 Int。