Is there ever a reason to use Scala's StringLi

2020-07-05 06:55发布

问题:

Scala's StringLike has the method replaceAllLiterally(literal: String, replacement: String): String

This seems to be very similar in effect to Java's String with the method String replace(CharSequence target, CharSequence replacement).

Is there ever a reason to use the Scala version?

(Not going through the regex compile step would seem to enable Java's version to be faster, though I haven't benchmarked that)

回答1:

It's to avoid collision with replace on StringBuilder. StringBuilder is also a StringLike. Why the StringBuilder replace wasn't the one to be changed, I'm not sure.

There's no reason to use it on strings unless you want to handle any StringLike (i.e. both wrapped strings and their builders).



回答2:

It is very helpful to use Scala's method to avoid the confusion of being buried by escape characters. Stack Overflow users @pedrofurla and @rampart81 explain it all quite well here.



标签: java scala