1

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?

nobeh
  • 9,784
  • 10
  • 49
  • 66

1 Answers1

3

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
  }
}
dhg
  • 52,383
  • 8
  • 123
  • 144
  • Now, my question is what's the meaning of `()` wrapping around `AnyRef*`? – nobeh Jun 22 '12 at 14:14
  • 1
    They're just parentheses to tell Scala that `AnyRef*` should be taken fully as the function's input. Just like how `(1+2)*3` tell you that `1+2` should be taken fully as the first argument to `+`. – dhg Jun 22 '12 at 14:20
  • 1
    @nobeh The parenthesis around `AnyRef*` is the standard when specifying input parameters to a function. Their absence in the case of single-parameter function is a syntactic sugar exception. – Daniel C. Sobral Jun 22 '12 at 19:46