נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
JavaJava

records, enums, sealed ו-pattern matchingrecords, enums, sealed & pattern matching

מפגש 23: records לנתונים, enums עם התנהגות, sealed interfaces, ו-switch עם תבניות (Java 21).Session 23: records for data, enums with behavior, sealed interfaces, and switch with patterns (Java 21).

מה נעשה היוםToday's plan

  • מונחיםTerms
  • record: מחלקת נתונים בשורה אחתrecord: a data class in one line
  • enum עם התנהגותAn enum with behaviour
  • sealed, records ו-switch עם תבניותsealed, records and a pattern switch
  • סוג חדש, switch ישןA new kind, an old switch
  • טעויות נפוצותCommon mistakes
נושאTopic 1

מונחיםTerms

המונחים של המפגשThis session's terms

  • record: record Book(String title, int year) {}:record: record Book(String title, int year) {}:
  • בנאי מקוצר: Book { if (year < 0) throw ...; } בתוך record:compact constructor: Book { if (year < 0) throw ...; } inside a record:
  • enum: טיפוס עם רשימה סגורה של ערכים:enum: A type with a closed list of values:
  • sealed: sealed interface Shape permits Circle, Rect:sealed: sealed interface Shape permits Circle, Rect:
  • switch עם תבניות: switch (s) { case Circle c -> ...; } בודק את הסוג ונותן משתנה מוכן.pattern switch: switch (s) { case Circle c -> ...; } checks the type and gives a ready variable.
  • פירוק record: case Rect(double w, double h) -> מפרק את ה-record לשדות שלו ישר בתוך ה-case.record pattern: case Rect(double w, double h) -> takes the record apart into its fields right in the case.
נושאTopic 2

record: מחלקת נתונים בשורה אחתrecord: a data class in one line

record: מחלקת נתונים בשורה אחתrecord: a data class in one line

  • record Book נותן toString, getters (title(), בלי get), ו-equals/hashCode לפי כל השדות, ולכן ה-Set רואה ספר אחד.record Book gives a toString, getters (title(), no get), and equals/hashCode by every field, so the Set sees one book.
  • הבנאי המקוצר בודק את השנה.The compact constructor checks the year.
נושאTopic 3

enum עם התנהגותAn enum with behaviour

enum עם התנהגותAn enum with behaviour

  • כל ערך של Genre נוצר פעם אחת עם הנתונים שלו.Each Genre value is created once with its data.
  • values() מחזירה את כולם לפי הסדר, ו-valueOf הופך טקסט לערך.values() returns them all in order, and valueOf turns text into a value.
נושאTopic 4

sealed, records ו-switch עם תבניותsealed, records and a pattern switch

sealed, records ו-switch עם תבניותsealed, records and a pattern switch

  • Shape סגור: יש רק Circle ו-Rect.Shape is sealed: there's only Circle and Rect.
  • ה-switch מפרק כל record (פירוק record), ו-when מוסיף תנאי (ריבוע).The switch takes each record apart (record pattern), and when adds a condition (a square).
  • אין default: javac יודע שכיסינו הכול.There's no default: javac knows we covered everything.
נושאTopic 5

סוג חדש, switch ישןA new kind, an old switch

סוג חדש, switch ישןA new kind, an old switch

  • הוספנו Triangle לרשימת ה-permits, ושכחנו לעדכן את ה-switch.We added Triangle to the permits list and forgot to update the switch.
  • javac לא נותן לזה לעבור: זה היתרון של כיסוי מלא.javac won't let it pass: that's the payoff of exhaustiveness.
נושאTopic 6

טעויות נפוצותCommon mistakes

טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

  • the switch expression does not cover all possible input values:the switch expression does not cover all possible input values:
נושאTopic 7

פרויקט מדףShelf project

הצעד של היום בפרויקט מדףToday's step in the Shelf project

  • מדף, צעד 23: סוגי פריטים כ-sealed ו-recordsShelf, step 23: item kinds as sealed types and records

record: record Book(String title, int year) {}:record: record Book(String title, int year) {}:

בנאי מקוצר: Book { if (year < 0) throw ...; } בתוך record:compact constructor: Book { if (year < 0) throw ...; } inside a record:

enum: טיפוס עם רשימה סגורה של ערכים:enum: A type with a closed list of values:

sealed: sealed interface Shape permits Circle, Rect:sealed: sealed interface Shape permits Circle, Rect:

switch עם תבניות: switch (s) { case Circle c -> ...; } בודק את הסוג ונותן משתנה מוכן.pattern switch: switch (s) { case Circle c -> ...; } checks the type and gives a ready variable.

פירוק record: case Rect(double w, double h) -> מפרק את ה-record לשדות שלו ישר בתוך ה-case.record pattern: case Rect(double w, double h) -> takes the record apart into its fields right in the case.

record Book נותן toString, getters (title(), בלי get), ו-equals/hashCode לפי כל השדות, ולכן ה-Set רואה ספר אחד.record Book gives a toString, getters (title(), no get), and equals/hashCode by every field, so the Set sees one book.

הבנאי המקוצר בודק את השנה.The compact constructor checks the year.

כל ערך של Genre נוצר פעם אחת עם הנתונים שלו.Each Genre value is created once with its data.

values() מחזירה את כולם לפי הסדר, ו-valueOf הופך טקסט לערך.values() returns them all in order, and valueOf turns text into a value.

Shape סגור: יש רק Circle ו-Rect.Shape is sealed: there's only Circle and Rect.

ה-switch מפרק כל record (פירוק record), ו-when מוסיף תנאי (ריבוע).The switch takes each record apart (record pattern), and when adds a condition (a square).

אין default: javac יודע שכיסינו הכול.There's no default: javac knows we covered everything.

הוספנו Triangle לרשימת ה-permits, ושכחנו לעדכן את ה-switch.We added Triangle to the permits list and forgot to update the switch.

javac לא נותן לזה לעבור: זה היתרון של כיסוי מלא.javac won't let it pass: that's the payoff of exhaustiveness.

the switch expression does not cover all possible input values:the switch expression does not cover all possible input values:

מדף, צעד 23: סוגי פריטים כ-sealed ו-recordsShelf, step 23: item kinds as sealed types and records

record P(int x, int y) {}. איך קוראים את x?record P(int x, int y) {}. How do you read x?

  • p.getX()p.getX()
  • p.x()p.x()
  • p.xp.x
  • P.xP.x

p.x()p.x()

אפשר לשנות שדה של record אחרי שנוצר?Can you change a record's field after it's created?

  • כן, עם setter אוטומטיYes, with an automatic setter
  • לא: השדות final. יוצרים record חדשNo: the fields are final. You create a new record
  • כן, דרך השדה ישירותYes, through the field directly
  • רק בתוך switchOnly inside a switch

לא: השדות final. יוצרים record חדשNo: the fields are final. You create a new record

מה היתרון של sealed ב-switch?What's the benefit of sealed in a switch?

  • switch רץ מהר יותרThe switch runs faster
  • javac יודע את כל האפשרויות ומזהיר כשחסר casejavac knows every possibility and complains when a case is missing
  • אפשר לרשת ממנו מכל מקוםAnyone can extend it
  • אין יתרוןThere's no benefit

javac יודע את כל האפשרויות ומזהיר כשחסר casejavac knows every possibility and complains when a case is missing

נקודה כ-recordA point as a record

  • record Point(int x, int y) עם מתודה distance() ומתודה withX(int) שמחזירה נקודה חדשה.record Point(int x, int y) with a distance() method and a withX(int) method returning a new point.

דירוג שבודק את עצמוA rating that checks itself

גדלים ומחיריםSizes and prices

  • enum Size { SMALL(10), MEDIUM(14), LARGE(18) } עם price().enum Size { SMALL(10), MEDIUM(14), LARGE(18) } with price().

סוף שבועThe weekend

  • enum Day (ראשון עד שבת).enum Day (Sunday to Saturday).

צייד באגים: case חסרBug hunter: a missing case

  • התוכנית מהתזכורת לא מתקמפלת.The program from the refresher doesn't compile.

מה למדנוWhat we learned

  • record: record Book(String title, int year) {}:record: record Book(String title, int year) {}:
  • record Book נותן toString, getters (title(), בלי get), ו-equals/hashCode לפי כל השדות, ולכן ה-Set רואה ספר אחד.record Book gives a toString, getters (title(), no get), and equals/hashCode by every field, so the Set sees one book.
  • כל ערך של Genre נוצר פעם אחת עם הנתונים שלו.Each Genre value is created once with its data.
  • Shape סגור: יש רק Circle ו-Rect.Shape is sealed: there's only Circle and Rect.
  • הוספנו Triangle לרשימת ה-permits, ושכחנו לעדכן את ה-switch.We added Triangle to the permits list and forgot to update the switch.
  • the switch expression does not cover all possible input values:the switch expression does not cover all possible input values:

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

נבנה על ידיBuilt by Ariel Yohimovich