nobeh
nobeh

Reputation: 10039

Function with varargs in constructor

I am trying to get this working in Scala:

class MyClass(some: Int, func: AnyRef* => Int) {
}

The above code won't compile (why?) but the following does:

class MyClass(some: Int, func: Seq[AnyRef] => Int) {
}

That's OK but are the two equivalent? And if so, then how can I then use func inside MyClass?

Upvotes: 1

Views: 150

Answers (1)

dhg
dhg

Reputation: 52681

The first one (with varargs) works if you use parentheses:

class MyClass(some: Int, func: (AnyRef*) => Int)

The two forms of func, however are not the same. The first version takes a vararg input, so you would call it like func(a,b,c,d), but the second version takes a Seq as input, so you would call it like func(Seq(a,b,c,d)).

Compare this:

class MyClass(some: Int, func: (AnyRef*) => Int) {
  def something() = {
    func("this","and","that") + 2
  }
}

to this:

class MyClass(some: Int, func: Seq[AnyRef] => Int) {
  def something() = {
    func(Seq("this","and","that")) + 2
  }
}

Upvotes: 3

Related Questions