Sumit Pal
Sumit Pal

Reputation: 443

Scala - Type Mismatch Found Unit : required Array[Int]

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 ?

Upvotes: 3

Views: 6139

Answers (3)

elm
elm

Reputation: 20405

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)

Upvotes: 2

TheCopycat
TheCopycat

Reputation: 401

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"

Upvotes: 0

Lee
Lee

Reputation: 144106

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

Upvotes: 10

Related Questions