okinawa

IT勉強メモ

メソッドーチェーンとは

・決まり

チェーンでつなぐメソッドは自身のオブジェクトの参照を返す必要がある。(return this;)

       // toString()もtrim()もstrip()も returnはthis
        String s = "あいうえお".toString().trim().strip();
        
        // 最後に繋げるメソッドはthisを返さなくても良い
        char c = "あいうえお".toString().trim().strip().charAt(3);
        
        // これと同じ
        String s2 = "あいうえお".toString();
        s2 = s2.trim();
        s2 = s2.strip();

-------------------------------------------
public String toString() {
            return this;
        }

        public String trim() {
            String ret = isLatin1() ? StringLatin1.trim(value)
                                    : StringUTF16.trim(value);
            return ret == null ? this : ret;
        }
        
        public String strip() {
            String ret = isLatin1() ? StringLatin1.strip(value)
                                    : StringUTF16.strip(value);
            return ret == null ? this : ret;
        
        public char charAt(int index) {
            if (isLatin1()) {
                return StringLatin1.charAt(value, index);
            } else {
                return StringUTF16.charAt(value, index);
            }
        }