RDJ
RDJ

Reputation: 4122

Scala: Add values to sortedSet or array using for loop

For a specific application I need to add integers from a non-sorted array to an empty sortedSet using a for loop. (Or to a new array which is sorted). I know this can be done avoiding loops but I want to use a loop in this instance.

This code seems broadly right:

def minFor(r: Array[Int]): Int = {
    var itsSorted = collection.SortedSet.empty[Int]
    for(i <- 0 to r.length)
      itsSorted = itsSorted + i
}

But no matter how I tweak it I always end up with a mismatch error:

error: type mismatch;
 found   : Unit
 required: Int
           for(i <- 0 to r.length)

How do I return a sorted array or set via a loop?

Upvotes: 2

Views: 835

Answers (1)

vitalii
vitalii

Reputation: 3365

Your function minFor should return Int. But your last statement in the function

for(i <- 0 to r.length)
  itsSorted = itsSorted + i

returns Unit. So compiler complains that types do not match. To return the actual sorted set you should change your function as:

def minFor(r: Array[Int]) = {
  var itsSorted = collection.SortedSet.empty[Int]
  for(i <- 0 to r.length)
    itsSorted = itsSorted + i
  itsSorted
}

Upvotes: 4

Related Questions