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

看板java作者 (sbr)時間16年前 (2009/03/12 21:58), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/8 (看更多)
※ 引述《macbuntu (邀怪)》之銘言: : 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 的東西, 我覺得這個理由有點牽強,如果你實作 interface 裡某個 method,而你的實作永遠 要 return null,你可以很簡單地(不靠較深的 engineering/tool)先宣告一個 local variable: public Object visit(Node f) { final Object ret = null; if (...) { // some shortcut ... return ret; } // normal condition ... ... return ret; } 或者是 public Object visit(Nodef) { visitImpl(Node f); return null; } private void visitImpl(Node f) { // your implementation here } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.130.21 ※ 編輯: sbrhsieh 來自: 218.173.130.21 (03/12 21:59)
文章代碼(AID): #19kHKV-X (java)
討論串 (同標題文章)
文章代碼(AID): #19kHKV-X (java)