Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
language:java [2026/09/01 05:28] ledyxlanguage:java [2026/09/01 06:04] (current) – Pattern Matching ledyx
Line 49: Line 49:
 **여러 줄에 걸친 문자열**을 만들기 위한 새로운 문법 **여러 줄에 걸친 문자열**을 만들기 위한 새로운 문법
  
-12에서 preview였다가 15에서 정식 문법으로 승격+12에서 preview였다가 15에서 정식 기능으로 승격
  
 <sxh java> <sxh java>
Line 59: Line 59:
   BC   BC
   DEF"""   DEF"""
 +</sxh>
 +
 +=== Switch Expression 개선 ===
 +
 +12에서 preview였다가 14에서 정식 기능으로 승격
 +
 +<sxh java>
 +    private String calculateTestGrade1(int score) {
 +        return switch (score) {
 +            case 5:
 +                yield "A";
 +            case 4, 3:
 +                yield "B";
 +            case 2:
 +                yield "C";
 +            default:
 +                yield "F";
 +        };
 +    }
 +    
 +    private String calculateTestGrade2(int score) {
 +        return switch (score) {
 +            case 5 -> "A";
 +            case 4, 3 -> "B";
 +            case 2 -> {
 +                System.out.println("C!");
 +                yield "C";
 +            }
 +            default -> "F";
 +        };
 +    }
 +</sxh>
 +
 +==== 'Instance of' Pattern Matching ====
 +
 +14에서 preivew였다가 16에서 정식 기능으로 승격
 +
 +<sxh java>
 +    public String say(Animal animal) throws IllegalAccessException {
 +        if (animal instanceof Dog dog) {
 +            return dog.bark();
 +        } else if (animal instanceof Cat cat) {
 +            return cat.purr();
 +        }
 +
 +        throw new IllegalAccessException();
 +    }
 +    
 +    // 아래처럼 부정인 경우 Scope가 괄호 밖까지 확장 가능
 +    public String sayIfDog(Animal animal) throws IllegalAccessException {
 +        if (!(animal instanceof Dog dog)) {
 +            throw new IllegalAccessException();
 +        }
 +
 +        return dog.bark();
 +    }
 +
 +
 +    public interface Animal {
 +    }
 +
 +    public static class Dog implements Animal {
 +        public String bark() {
 +            return "Dog barking...";
 +        }
 +    }
 +
 +    public static class Cat implements Animal {
 +        public String purr() {
 +            return "Cat purring...";
 +        }
 +    }
 </sxh> </sxh>
language/java.txt · Last modified: by ledyx · Currently locked by: ledyx