3
votes

Why does the method give a compile error in NetBeans

( error in question -- Type Mismatch Found Unit : required 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)
  }

I know that if there was a if clause - and no else clause - then why we get the type mismatch.

However, I am unable to resolve this above error - unless I add this line

return x

The error is not happening because the compiler thinks what happens if n <= 0 I tried writing the function with n = 10 as hardcoded

Thoughts ?

3
The last statement for in your function returns Unit, but return type is Array[Int]. Hence the error. So just put x as the last statement in the function. Check @Lee's answer below.tuxdna

3 Answers

10
votes

Your for comprehension will be converted into something like:

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

Since foreach returns (), the result of your for comprehension is (), so the result of the entire function is () since it is the last expression.

You need to return the array x instead:

for(i <- 0 to x.length-1)
        x(i) = scala.util.Random.nextInt(n)
x
2
votes

Yet another one,

def createArray(n: Int): Array[Int] = Array.fill(n) { scala.util.Random.nextInt(n) }

Then, for instance

val x: Array[Int] = createArray(10)
0
votes

You could do something cleaner in my own opinion using yield :

def createArray(n:Int):Array[Int] =
  (for(i: Int <- 0 to n-1) yield scala.util.Random.nextInt(n)).toArray

This will make a "one lined function"