[英]Scala type mismatch - found: Unit required: Array[String]
I do not understand why Scala complains about a type error in the following example: 我不明白为什么Scala在以下示例中抱怨类型错误:
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. 注意:我知道if语句返回类型Unit,因为没有指定其他类型。 But I can;t see that that would affect the type of my array.
但是我看不到那会影响我的数组类型。
Return type of scala.util.Sorting.quickSort(AllRanges)
is Unit
. scala.util.Sorting.quickSort(AllRanges)
返回类型为Unit
。 But, GetRanges
requires Array[String]
但是,
GetRanges
需要Array[String]
def GetRanges(RangeString1: String): Array[String] = {
val GetOneRange = "\\d+\\-\\d+".r;
Here is quickSort
for sorting Arrays 这是用于对数组进行排序的
quickSort
/** 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.
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). quickSort()
改变AllRanges
的位置,只返回Unit
,但是您已指定GetRanges()
返回Array[String]
,就像quickSort()
返回一个Array
(不是)。
You can fix your code by changing it to something like this (nb. you don't need to specify return
): 您可以通过将代码更改为以下代码来修复代码(nb。您无需指定
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: FWIW,您也可以通过执行以下操作来避免使用
f_stringNullEmpty
和数组并置:
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]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.