Scala - Type Mismatch Found Unit : required Array[Int]
mismatch, scala, types
Solution
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
Problem
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 ?