Why do the StringBuffer and StringBuilder append methods discard the value returned by the super call

This is a question of curiosity. Today I looked at the implementation StringBuilderand StringBuffer. Here's the method append():

public StringBuilder append(String str) {
    super.append(str);
    return this;
}

AbstractStringBuilder.append(str)also returns this. Are there any advantages of discarding the return value (in StringBuilder.append(..)) and returning thisagain, instead of returning the return value of the call superfor the current specific implementation.

+3
source share
3 answers

My first thought is that casting can be expensive, so if it could be avoided it would be better.

+7
source

I'm not sure if this is due to the cost of casting.

, , , , .

public StringBuilder append(String str) {
    super.append(str);

    // do something more?

    return this;
}

IDE . .

+3

Because

public StringBuilder append(String str) {
    return (StringBuilder) super.append(str);
}

pretty ugly. It is not yet shorter.

(There are languages ​​that support this directly . Something like:

abstract class AbstractStringBuilder{
  type T = this.type
  def append(str : String) : T = ...
}

abstract class StringBuilder{
  //already defined by AbstractStringBuilder return type is StringBuilder
}

)

+2
source

Source: https://habr.com/ru/post/1726707/


All Articles