[分享] 原來 Void 可以這樣用
以前一直覺得 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
推
03/12 20:39, , 1F
03/12 20:39, 1F
※ weii:轉錄至看板 SFFamily 03/12 23:55
討論串 (同標題文章)
以下文章回應了本文 (最舊先):
完整討論串 (本文為第 1 之 8 篇):