Scala - 发现类型不匹配的单元 : required Array[Int]

标签 scala types mismatch

为什么该方法在 NetBeans 中给出编译错误

(有问题的错误 - 找到的类型不匹配单位:必需的 Array[Int] )

  def createArray(n:Int):Array[Int] =
  {
      var x = new Array[Int](n)
      for(i <- 0 to x.length-1)
        x(i) = scala.util.Random.nextInt(n)
  }

我知道如果有 if 子句 - 没有 else 子句 - 那么为什么我们会得到类型不匹配。

但是,我无法解决上述错误 - 除非我添加这一行

返回 x

错误没有发生,因为编译器认为如果 n <= 0 会发生什么
我尝试使用 n = 10 作为硬编码编写函数

想法?

最佳答案

您的 for理解将被转换成类似的东西:

0.to(x.length - 1).foreach(i => x(i) = scala.util.Random.nextInt(i))

foreach返回 () ,你的结果for领悟是() ,所以整个函数的结果是 ()因为它是最后一个表达式。

您需要改为返回数组 x:
for(i <- 0 to x.length-1)
        x(i) = scala.util.Random.nextInt(n)
x

关于Scala - 发现类型不匹配的单元 : required Array[Int],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21556954/

相关文章:

scala - 为什么 Spark 会失败并显示 "value write is not a member of org.apache.spark.sql.DataFrameReader [error]"?

scala - 创建 rx Observable 后添加元素

validation - R - 检查组分配的一致性,不同名称的组标签

iOS : mismatched translation

python-3.x - keras 多维度输入到 simpleRNN : dimension mismatch

java - 在 Scala 的案例类和类字段中使用 Optional 是否有代码味道?

python - 将 Apache Spark Scala 代码转换为 Python

c# - 使用Couchbase时发生类型转换错误

postgresql - Cast 产生 'Returned type character varying does not match expected type character varying(8)'

Postgresql 和 pgAdmin III,什么是字符变化 []