1. 經典的 switch:過去的限制
回顧一下過去的 switch(在 pattern matching 出現之前)。老實說,它相當保守。只能處理原始型別(int、char,之後加入 enum、String),如果你想處理不同的物件型別——就得寫長長的 if-else 鏈。
Object obj = ...;
if (obj instanceof String) {
String s = (String) obj;
System.out.println("字串: " + s);
} else if (obj instanceof Integer) {
Integer i = (Integer) obj;
System.out.println("整數: " + i);
} else if (obj == null) {
System.out.println("null!");
} else {
System.out.println("其他東西");
}
方便嗎?不太。程式碼冗長、容易出錯,而且一旦新增型別——又得改寫這條 if-else 鏈。
2. switch 中的 Pattern Matching:Java 17/21+ 的革新
Java 17(預覽)並在 Java 21+ 定案,引入了支援樣式比對(pattern matching)的全新 switch。現在 switch 不僅能處理原始型別,也能處理任意物件與型別,甚至是 null,並支援額外條件(guard 運算式)。
新語法:簡潔而強大
在 switch 中進行簡單的 pattern matching 範例:
Object obj = ...;
switch (obj) {
case String s -> System.out.println("字串: " + s);
case Integer i -> System.out.println("整數: " + i);
case null -> System.out.println("null!");
default -> System.out.println("其他東西");
}
這裡發生了什麼?
- 如果 obj 是字串,變數 s 會自動是 String 型別。
- 如果 obj 是整數,變數 i 會是 Integer。
- 如果 obj 是 null,會命中特別分支。
- 其他情況走 default。
為什麼這麼方便?
- 不需要手動轉型:Java 會幫你確保型別安全。
- 更少程式碼:沒有多餘的大括號、轉型與重複。
- 更安全:編譯器會檢查你是否涵蓋所有可能情況(特別是搭配 sealed 類別,我們稍後會談)。
- 容易擴充型別:只要再加一個 case 分支即可。
3. switch 中的 Pattern Matching:基礎範例
範例 1:處理不同型別
Object obj = 42;
switch (obj) {
case String s -> System.out.println("字串: " + s);
case Integer i -> System.out.println("整數: " + i);
case null -> System.out.println("這是 null");
default -> System.out.println("未知型別");
}
輸出:
整數: 42
範例 2:使用 guard 運算式(when)
有時僅知道型別還不夠——還想加上一些額外條件。
Object obj = "Hello, world!";
switch (obj) {
case String s when s.length() > 10 -> System.out.println("長字串: " + s);
case String s -> System.out.println("短字串: " + s);
case Integer i when i > 0 -> System.out.println("正數: " + i);
case Integer i -> System.out.println("非正數: " + i);
default -> System.out.println("其他東西");
}
輸出:
長字串: Hello, world!
請注意:
- when 是 guard 運算式,即 case 的額外條件檢查。
- 若條件不成立,會繼續檢查後續的 case。
範例 3:處理 null
Object obj = null;
switch (obj) {
case null -> System.out.println("這是 null!");
default -> System.out.println("不是 null");
}
輸出:
這是 null!
4. 在類別與繼承層級上的 switch Pattern Matching
在 switch 上進行 pattern matching,對於類別階層特別好用。
sealed interface Shape permits Circle, Rectangle, Square {}
final class Circle implements Shape {
final double radius;
Circle(double radius) { this.radius = radius; }
}
final class Rectangle implements Shape {
final double width, height;
Rectangle(double width, double height) { this.width = width; this.height = height; }
}
final class Square implements Shape {
final double side;
Square(double side) { this.side = side; }
}
Shape shape = new Rectangle(2, 3);
String description = switch (shape) {
case Circle c -> "半徑為 " + c.radius;
case Rectangle r -> "矩形 " + r.width + "x" + r.height;
case Square s -> "正方形,邊長 " + s.side;
};
System.out.println(description);
輸出:
矩形 2.0x3.0
亮點:如果你使用 sealed 類別並涵蓋了所有變體,就不需要分支 default——編譯器知道不會有其他可能!
5. 在 record 類別與巢狀樣式中的 switch 使用
在 switch 中的 pattern matching 支援 record 類別與巢狀樣式(自 Java 21+ 起)。
record Point(int x, int y) {}
record Line(Point start, Point end) {}
Object obj = new Line(new Point(1, 2), new Point(3, 4));
String result = switch (obj) {
case Line(Point(int x1, int y1), Point(int x2, int y2)) ->
"線段從 (" + x1 + "," + y1 + ") 到 (" + x2 + "," + y2 + ")";
case Point(int x, int y) -> "點 (" + x + "," + y + ")";
default -> "未知物件";
};
System.out.println(result);
輸出:
線段從 (1,2) 到 (3,4)
6. switch pattern matching 的特性與限制
變數只在對應的 case 內可用
在樣式中宣告的變數(例如 String s),只存在於對應的 case 區塊內。在其外部不可存取。
switch (obj) {
case String s -> System.out.println(s); // 這裡看得到 s
// System.out.println(s); // 這裡會編譯錯誤!
}
處理 null
- 在舊的 switch(物件)中,傳入 null 會拋出 NullPointerException。
- 在新的 pattern matching switch 中,可以透過 case null 顯式處理 null。
Guard 運算式(when)
額外條件(when)只在表達式風格的 switch 中可用(箭頭語法 ->)。
case String s when s.isEmpty() -> System.out.println("空字串");
對 JDK 與 IDE 的需求
- switch 的 pattern matching 是 Java 17(預覽)與 Java 21+(穩定)的功能。
- 要使用它需要 JDK 21,以及支援新功能的 IDE(例如 IntelliJ IDEA 2023+)。
7. 在實際應用中的 pattern matching switch
來看一個教學範例——簡單的任務追蹤器。假設你有一個抽象的任務型別與它的多種實作:
sealed interface Task permits SimpleTask, DeadlineTask, MeetingTask {}
final class SimpleTask implements Task {
final String description;
SimpleTask(String description) { this.description = description; }
}
final class DeadlineTask implements Task {
final String description;
final java.time.LocalDate deadline;
DeadlineTask(String description, java.time.LocalDate deadline) {
this.description = description;
this.deadline = deadline;
}
}
final class MeetingTask implements Task {
final String topic;
final java.time.LocalTime time;
MeetingTask(String topic, java.time.LocalTime time) {
this.topic = topic;
this.time = time;
}
}
所有邏輯集中在一個精簡的 switch:
Task task = new DeadlineTask("提交專案", java.time.LocalDate.of(2024, 7, 1));
String info = switch (task) {
case SimpleTask st -> "一般任務: " + st.description;
case DeadlineTask dt -> "具截止日的任務: " + dt.description + ", 截止至 " + dt.deadline;
case MeetingTask mt -> "會議: " + mt.topic + " 在 " + mt.time;
};
System.out.println(info);
輸出:
具截止日的任務: 提交專案, 截止至 2024-07-01
8. 使用 pattern matching switch 的常見錯誤
錯誤 №1:忘了處理 null。 如果你沒有加上 case null,而 obj 可能為 null——就會得到 MatchException(或在舊式 switch 中得到 NullPointerException)。只要有可能,務必顯式處理 null。
錯誤 №2:沒有涵蓋 sealed 類別的所有子型別。 如果使用了 sealed 類別,卻沒有在 switch 中涵蓋所有變體,編譯器會報錯或要求提供 default 分支。擴充階層時,別忘了新增對應的 case。
錯誤 №3:樣式變數在 case 區塊外不可用。 在樣式中宣告的變數只存在於箭頭區塊內,嘗試在該區塊之外使用會導致編譯錯誤。
錯誤 №4:在舊版 JDK 或 IDE 中使用新功能。 在 switch 中使用 pattern matching 需要 Java 21+ 與 IDE 的相應支援。如果使用舊版本——可能出現編譯錯誤或不正確的提示。
錯誤 №5:對 guard 運算式的混淆。 嘗試在舊式區塊 switch 中使用 when?不行。guard 僅適用於箭頭語法 ->。
錯誤 №6:在開放階層上忘了 default 分支。 如果你的 switch 不只處理 sealed 類別,務必加入 default——否則不一定涵蓋所有情況。
GO TO FULL VERSION