Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no StringBuilder.+=(String) in Scala?

Tags:

types

scala

This behavior seems to be broken (I am using Scala 2.9.1)

var b= new StringBuilder

These are OK:

b+='a'
b.append('b') 
b.append("de")

This produces compile error:

b+="de"

Any idea as to why only StringBuilder#+=(c: Char) exists whereas both StringBuilder#append(c:Char) and StringBuilder#append(s:String) happily co-exist? What is wrong with declaring and implementing StringBuilder#+=(s: String)?

Is it oversight or some deeper problem in the Scala type system?

like image 697
Sasha O Avatar asked Jul 24 '12 18:07

Sasha O


People also ask

Is a StringBuilder a string?

StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters.

What is string builder in Scala?

Companion object StringBuilderA builder for mutable sequence of characters. This class provides an API mostly compatible with java. lang. StringBuilder , except where there are conflicts with the Scala collections API (such as the reverse method.)

Are strings mutable in Scala?

In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified.

Does StringBuilder create new string?

StringBuilder will only create a new string when toString() is called on it. Until then, it keeps an char[] array of all the elements added to it. Any operation you perform, like insert or reverse is performed on that array.


1 Answers

Try b ++= "de". A String is considered a collection of Chars.

like image 105
Jean-Philippe Pellet Avatar answered Oct 21 '22 10:10

Jean-Philippe Pellet