简体   繁体   中英

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 ?

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

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)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM