M.S.Visser
M.S.Visser

Reputation: 81

Scala type mismatch - found: Unit required: Array[String]

I do not understand why Scala complains about a type error in the following example:

def GetRanges(RangeString1: String): Array[String] = {
    val GetOneRange = "\\d+\\-\\d+".r;
    var AllRanges = new Array[String](0);
    if (!f_stringNullEmpty(RangeString1)) {
      GetOneRange.findAllIn(RangeString1).matchData.foreach(
        m => AllRanges = AllRanges ++ Array[String](m.group(0)) // Explicit casting to Array[String]
      )
    }
    return scala.util.Sorting.quickSort(AllRanges);
}

the error I receive is:

 notebook:38: error: type mismatch;
 found   : Unit
 required: Array[String]
 return scala.util.Sorting.quickSort(AllRanges);
                                    ^

Apparently, iterating through the regex results and adding them to the array, causes a type change. But why? Or did I miss something more fundamental?

Note: I understand that the if statement returns a type Unit, because no else was specified. But I can;t see that that would affect the type of my array.

Upvotes: 0

Views: 2545

Answers (2)

Joey
Joey

Reputation: 11

quickSort() mutates AllRanges in place and just returns Unit, but you've specified that GetRanges() returns Array[String] as if quickSort() was returning an Array (it's not).

You can fix your code by changing it to something like this (nb. you don't need to specify return):

scala.util.Sorting.quickSort(AllRanges)
AllRanges

FWIW, you can also avoid using f_stringNullEmpty and the array concatenation by doing something like this instead:

def getRanges(s: String): Array[String] = {
  val p = """\d+\-\d+""".r
  Option(s).filter(_.nonEmpty).map(p.findAllIn) match {
    case Some(matches) if matches.nonEmpty =>
      val m = matches.toArray[String]
      scala.util.Sorting.quickSort(m)
      m
    case _ =>
      Array.empty[String]
  }
}

Upvotes: 0

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Return type of scala.util.Sorting.quickSort(AllRanges) is Unit. But, GetRanges requires Array[String]

def GetRanges(RangeString1: String): Array[String] = {
val GetOneRange = "\\d+\\-\\d+".r;

Here is quickSort for sorting Arrays

 /** Sort array `a` with quicksort, using the Ordering on its elements.
    * This algorithm sorts in place, so no additional memory is used aside from
    * what might be required to box individual elements during comparison.
    */
  def quickSort[K: Ordering](a: Array[K]): Unit = {
    // Must have iN >= i0 or math will fail.  Also, i0 >= 0.

Upvotes: 1

Related Questions