Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การใช้งาน Underscore Keyword ใน Java 9

Underscore (_) กลายเป็น Reserved Keyword

ใน Java ก่อนหน้า underscore (_) ใช้เป็น identifier หรือ variable name ได้ ตั้งแต่ Java 9 underscore เป็น reserved keyword ห้ามใช้เป็น identifier/ตัวแปร

ผลลัพธ์ถ้าใช้

Compile-time error: error: as of release 9, '_' is a keyword, and may not be used as an identifier

ตัวอย่าง

public class UnderscoreKeywordTest {
    public static void main(String args[]) {
        int _ = 50;           // Compile error
        System.out.println(_); // Compile error
    }
}

Output (Compile Error)

UnderscoreKeywordTest.java:3: error: as of release 9, '_' is a keyword, and may not be used as an identifier
int _ = 50;
^
UnderscoreKeywordTest.java:4: error: as of release 9, '_' is a keyword, and may not be used as an identifier
System.out.println(_);

เหตุผล

สำรองไว้สำหรับฟีเจอร์อนาคต เช่น pattern matching, lambda parameters ที่ไม่ได้ใช้ (unused parameters) ใน Java 10+ ใช้ _ แทน unused lambda parameter ได้

สรุป

ห้ามใช้ _ เป็น variable name ใน Java 9+ ต้อง rename variables ที่ใช้ _ แล้ว