Strange ArrayBuffer Behavior

Can someone explain to me why the padTo method from ArrayBuffer is not working as I expected? In this example, I would expect the array created by toArray to have a length of 10.

scala> val b = new scala.collection.mutable.ArrayBuffer[Byte] b: scala.collection.mutable.ArrayBuffer[Byte] = ArrayBuffer() scala> b.append(2) scala> b res1: scala.collection.mutable.ArrayBuffer[Byte] = ArrayBuffer(2) scala> b.append(2) scala> b res3: scala.collection.mutable.ArrayBuffer[Byte] = ArrayBuffer(2, 2) scala> b.padTo(10,0) res4: scala.collection.mutable.ArrayBuffer[AnyVal] = ArrayBuffer(2, 2, 0, 0, 0, 0, 0, 0, 0, 0) scala> b.toArray res5: Array[Byte] = Array(2, 2) 
+4
source share
3 answers

Since padTo returns a new sequence (it does not mutate an existing one):

Try

 var c = b.padTo(10,0) c.toArray 

See also: https://issues.scala-lang.org/browse/SI-2257

+5
source

If you look at the documentation , you will see the difference:

def append (elems: A*): Unit

Use case (append): adds these elements to this buffer.

def padTo (len: Int, elem: A): ArrayBuffer[A]

Use Case (padTo): Adds the value of an element to this buffer array until the specified target length is reached.

Add returns Unit , and padTo returns a new ArrayBuffer .

+4
source

From scaladoc :

returns: a new collection of type consisting of all elements of this massive buffer, followed by a minimum number of entries of elem so that the resulting set has a length of at least len.

So b, even modified, does not change.

+2
source

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


All Articles