Re: [分享] 原來 Void 可以這樣用
※ 引述《macbuntu (邀怪)》之銘言:
: 以前一直覺得 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) {
: ...
: }
: }
其實你描述的這些現象跟 java.lang.Void 無關。
你只要定義一個只有 private constructor(無法 instantiate instance) 的 final
class 就會有你描述的特性。之所以只能 return null 是因為你無法 return 一個
instance(return type 無法被繼承,無法建構出 object)。
java.lang.Void 當初的設計並不是特意讓它有你形容的這個特性。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.130.21
推
03/12 21:39, , 1F
03/12 21:39, 1F
推
03/12 22:15, , 2F
03/12 22:15, 2F
→
03/12 22:18, , 3F
03/12 22:18, 3F
→
03/12 22:20, , 4F
03/12 22:20, 4F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 8 篇):