Re: [分享] 原來 Void 可以這樣用

看板java作者 (sbr)時間16年前 (2009/03/12 21:36), 編輯推噓2(202)
留言4則, 3人參與, 最新討論串2/8 (看更多)
※ 引述《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
也是啦, 不過有個 Void 可以借用語意挺好的
03/12 22:15, 2F

03/12 22:18, , 3F
不然建個 class Null {private Null(){}} 就有點邪惡了
03/12 22:18, 3F

03/12 22:20, , 4F
我想程式怎麼寫不重要,你覺得有面子就好...
03/12 22:20, 4F
文章代碼(AID): #19kG_pW8 (java)
討論串 (同標題文章)
文章代碼(AID): #19kG_pW8 (java)