在 GitHub 上編輯此頁面

已移除:弱一致性 - 更多詳細資訊

為了簡化底層類型理論,Scala 3 完全移除 弱一致性 的概念。相反地,它在將類型指定給常數表達式時提供更大的彈性。新的規則為

  • 如果表達式清單 Es 出現在下列其中一項中

    • 變數參數的元素,或
    • if-then-else 或 match 表達式的選項,或
    • try 表達式的本體和 catch 結果,
  • 而且所有表達式都有基本數值類型,但它們並非都有相同的類型,

  • 嘗試下列動作

    • 將表達式 Es 分割成一方面為 Int 常數,另一方面為所有其他表達式,
    • 如果所有其他表達式具有相同的數字類型 T(可能是 ByteShortCharIntLongFloatDouble 之一),可能在擴充後,而且如果沒有任何 Int 文字在轉換為 T 時會造成精度損失,則它們會因此轉換(其他表達式無論如何都保持不變),
    • 否則,表達式 Es 會保持不變使用。

    精度損失會發生在

    • 常數 cInt -> Float 轉換中,如果 c.toFloat.toInt != c
    • 常數 cInt -> Byte 轉換中,如果 c.toByte.toInt != c
    • 常數 cInt -> Short 轉換中,如果 c.toShort.toInt != c

範例

inline val b = 33
def f(): Int = b + 1
Array(b, 33, 5.5)      : Array[Double] // b is an inline val
Array(f(), 33, 5.5)    : Array[AnyVal] // f() is not a constant
Array(5, 11L)          : Array[Long]
Array(5, 11L, 5.5)     : Array[AnyVal] // Long and Double found
Array(1.0f, 2)         : Array[Float]
Array(1.0f, 1234567890): Array[AnyVal] // loss of precision
Array(b, 33, 'a')      : Array[Char]
Array(5.toByte, 11)    : Array[Byte]
在本文中