Home > Blockchain >  Scala infinite loop
Scala infinite loop

Time:11-15

So I am new to scala and from what I've found online, scala does not update variable like other languages do. I am trying to change a variable in the while loop but it seems like it is not changing. I have a mutable ArrayBuffer that is holding key,value pairs and is declared like:

val array1 = mutable.ArrayBuffer[Option[IndexedSeq[(K,V)]]]()

It is storing sorted arrays based on the "K" value which is always an int. I am trying to loop though the layers of array1 by doing:

var i=0
var counter = 0
while(array1(i).isDefined){
    counter  = 1
    i  = 1}

However, this results in an infinite loop annd I suspect i is not changing and I dont know why.

CodePudding user response:

You'll do well to forget a lot of the low-level C paradigms when you're working in a high-level language like Scala. It's just going to steer you wrong.

If you have an iterable thing (such as an ArrayBuffer, a List, or anything else that vaguely implies a collection of things), you can iterate over it with

myArray.foreach { element => ... }

or, if you want to build a new collection out of the result

val myNewArray = myArray.map { element => ... }

To remove some elements based on an arbitrary condition, consider

val myNewArray = myArray.filter { element => ... }

The "always throw it in a while / for loop" approach is very C-centric, and in Scala we have tons of higher-level, more expressive tools to do the work we want to do. Scala still has a while loop, but you seldom need to use it, simply because there are so many built-in functions that express the common looping paradigms for you.

A functional programmer can look at

val myNewArray = myArray.map { _   1 }

and immediately see "aha, we're iterating and making a new array by adding one to each element", and it breaks the problem down a ton. The "equivalent" code in C-style would be something like

val myNewArray = ArrayBuffer()
var i = 0
while (i < myArray.size) {
  myNewArray  = (myArray(i)   1)
  i  = 1
}

The basic concept is still the same: "add one to each element", but there's a ton more to parse here to get to the actual idea of the code. This code doesn't immediately read "add one to elements of a list". It reads "okay, we're making an array and using a local variable, and then we're doing something several times that looks like it's adding one and..."

  • Related