0

So, if I want to store 5 zeros in a sequence, and access them later through their index numbers, what type of a sequence should I use in Scala?

In Python i would do something like this:

listTest = list(0,0,0,0,0)
listTest[1] = 3
print(listTest)

-> 0,3,0,0,0

I realize a similar question is likely already answered to. Might be that I just don't know the right keywords to find one.

Astudent
  • 186
  • 1
  • 2
  • 16
  • An https://www.scala-lang.org/api/current/scala/collection/mutable/ArrayBuffer.html or a plain https://www.scala-lang.org/api/current/scala/Array.html would do – fusion Dec 29 '19 at 21:38

1 Answers1

2

Collections performance characteristics lists among others the following sequences that are mutable, and indexable in constant time

ArrayBuffer
ArraySeq
Array

Note how the document refers to indexing as applying. The reason for this is that in Scala element is accessed via apply method like so

val arr = ArrayBuffer(11, 42, -1)
arr.apply(1) // 42 
arr(1)       // sugared version of arr.apply(1) so also evaluates to 42

To decide which one to use consider


As a side-note, Python's list is conceptually different from Scala's List because former is array-based indexed collection with constant-time indexing, whilst latter is linked list collection with linear-time indexing.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98