精華區beta java 關於我們 聯絡資訊
以前一直覺得 Void (大的 Void 喔, 不是小的 void) 沒什麼用, 除了 reflection 時會用到以外, 平常的程式根本不需要. 寫 void func() 就很好了, 誰會想要寫 Void func()? 但是今天突然發現我還真的會想要寫 Void func(): interface A { public Object visit(Node f); } class B implements A { @Override public Void visit(Node f) { ... return null; // 任何不是 null 的 return 值都是 compile time error } } 在我的狀況, A 是一個由 code generator 產生的 visitor interface, 不能改, 我 implement 它時有些 method 不該 return 任何東西, 但因為 method 的內容很長 且 return 的點不只一個, 不小心會忘記, 而 interface 的關係我又不能用小 void, 這時候大 Void 就變得很有用了. 如果我弄錯了 return 不是 null 的東西, 就會變成 compile time error. Nice! 其實不只 return type 可以用 Void, argument type 也可以: class C { // 只能用 func(null) 來呼叫 public int func(Void o) { ... } } 但因為 Void 比任何其他型別都還來的 "specific", 所以除非你的 interface 就是 宣告 Void 當作 argument, 否則底下的子孫是不能用 Void 來 implement 的. 這我就真的想不到有甚麼狀況會需要宣告一個 Void 型別的 argument 了 :P -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.137.5.239