與 Java 的比較
Kotlin 解決的 Java 問題
Kotlin 修正了一系列 Java 存在的問題:
- Null 引用由類型系統控制。
- 沒有 Raw Types
- Kotlin 中的陣列是invariant (不變的)
- Kotlin 具有適當的函數類型,而不是 Java 的 SAM 轉換
- Use-site variance (使用點變異數),無需萬用字元 (Wildcards)
- Kotlin 沒有已檢查的 exceptions (例外)
- 用於唯讀和可變集合的單獨介面
Java 擁有的 Kotlin 沒有的
- Checked exceptions (已檢查的例外)
- 不是類別的 Primitive types (基本類型)。位元組碼在可能的情況下使用基本類型,但它們不是顯式可用的。
- Static members (靜態成員) 被 companion objects (伴生物件)、top-level functions (頂層函數)、extension functions (擴展函數) 或 @JvmStatic 取代。
- Wildcard-types (萬用字元類型) 被 declaration-site variance (宣告點變異數) 和 type projections (類型投影) 取代。
- Ternary-operator
a ? b : c
(三元運算符) 被 if expression (if 表達式) 取代。 - Records
- Pattern Matching
- package-private visibility modifier (可見性修飾符)
Kotlin 擁有的 Java 沒有的
- Lambda expressions (Lambda 表達式) + Inline functions (內聯函數) = 高效能的自訂控制結構
- Extension functions (擴展函數)
- Null-safety (Null 安全)
- Smart casts (智能轉換) (Java 16: Pattern Matching for instanceof)
- String templates (字串模板) (Java 21: String Templates (Preview))
- Properties (屬性)
- Primary constructors (主建構函數)
- First-class delegation (頭等委託)
- Type inference for variable and property types (變數和屬性類型的類型推斷) (Java 10: Local-Variable Type Inference)
- Singletons (單例)
- Declaration-site variance & Type projections (宣告點變異數 & 類型投影)
- Range expressions (範圍表達式)
- Operator overloading (運算符重載)
- Companion objects (伴生物件)
- Data classes (數據類)
- Coroutines (協程)
- Top-level functions (頂層函數)
- Default arguments (預設參數)
- Named parameters (具名參數)
- Infix functions (中綴函數)
- Expect and actual declarations (Expect 和 Actual 宣告)
- Explicit API mode (顯式 API 模式) 和 better control of API surface (更好地控制 API 介面)
接下來做什麼?
學習如何: