Technologeek
Technologeek

Reputation: 190

How to pass Arrays as arguments to a function in Scala?

forgive if this is too basic of a question,I'm pretty new to scala and been stuck at this particularly.

What I'm trying to achieve is,to have a function which takes an array as arguments,like so :

 evenOdd(1,2,3,4,5,6);  //where evenOdd is my function

The function definition looks like :

def evenOdd(x : Array[Int] = new Array[Int](6)){

}

It throws an error that too many arguments for the function.How can I achieve passing multiple array integers as fixed size in the function ?

Upvotes: 6

Views: 15025

Answers (3)

Nilesh Shinde
Nilesh Shinde

Reputation: 469

Check is an example for the passing array as an argument

object ArrayRotation {
  def main(args: Array[String]) {
    var arr = Array(1, 2, 3, 4, 5, 6, 7)

    call(arr)
  }
  def call(arr: Array[Int]) {
    for (i <- 0 to 1) {
      for (j <- 0 to arr.length - 2) {
        var temp = arr(j)
        arr(j) = arr(j + 1)
        arr(j + 1) = temp

      }

    }
    for (i <- 0 to arr.length - 1) {
      print(arr(i))
    }
  }

}

Upvotes: 1

Sohum Sachdev
Sohum Sachdev

Reputation: 1397

You were passing a varargs (read more about it here). However, your function evenOdd accepts an array of integers.

You have two ways to solve this:

  1. Make evenOdd function to accept varargs of integer. The drawback of this is that you cannot assign a default value for this:

    def evenOdd(x : Int*)

  2. Don't change the input paramters of evenOdd, but pass in an array of integer instead:

    evenOdd(Array(1,2,3,4,5,6))

Upvotes: 2

Ziyang Liu
Ziyang Liu

Reputation: 810

Either pass an Array to evenOdd:

evenOdd(Array(1, 2, 3, 4, 5, 6))

or define evenOdd as:

def evenOdd(x: Int*) = {...}

Upvotes: 9

Related Questions