2

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?

0

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - I understand that the Unit type is not correct. But I don't know how to return the desired data type - a sorted array or set - correctly. I'm new to Scala.
I have updated the answer. You can put itsSorted.head if you need to return only minimum element, or itsSorted.headOption if your Array can be empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.