تعبيرات switch ومطابقة الأنماط
في هذا الدرس 4 موضوعات
محتوى هذا الدرس مكتوب وينتظر المراجعة. يعرض المخطط أدناه ما سيغطيه، وسيُنشر بعد اعتماده.
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
في هذا الدرس
handle every case of a sealed type with a switch.
الموضوعات المخطط لها
- A switch expression returns a value and uses
->, with no fall-through. - A pattern in a case matches a type and gives it a name:
case Percentage p. - On a sealed type, the switch must cover all cases or it will not compile.
- Do not add
default: it hides the compile error when you add a new type. instanceofpatterns do the same for single checks:if (o instanceof String s).
تفاصيل المخطط المبدئي
عرض عملي
Money apply(Discount d, Money price) {
return switch (d) {
case Percentage p -> price.minusPercent(p.percent());
case FixedAmount f -> price.minus(f.amount());
case BuyXGetY b -> price; // handled per cart line
};
}اختبر فهمك
Why avoid default on a sealed switch?
أظهر الإجابة
It stops the compiler from warning you about a new, unhandled type.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.