Parameters List (*) in Scala

54 views
Skip to first unread message

Edmondo Porcu

unread,
Jan 12, 2012, 12:07:21 PM1/12/12
to scala-user
Dear all,
I have a problem with parameters list in Scala.... I obtain a type mismatch which I am not expecting:

def filterYears(toSkip: Range*) = skipSomething(12,toSkip);

def filterMonths(toSkip: Range*) = skipSomething(1,toSkip)


private def skipSomething( multiplier:Int,toSkip:Range*){}

Results in the following compiler error:

error: type mismatch;
found   : Range*
required: Range
def filterYears(toSkip: Range*) = skipSomething(12,toSkip);


error: type mismatch;
found   : Range*
required: Range
def filterMonths(toSkip: Range*) = skipSomething(1,toSkip)

What is the reason for that?

Best Regards

Sciss

unread,
Jan 12, 2012, 12:11:08 PM1/12/12
to Edmondo Porcu, scala-user
varargs (the last parameter with an asterisk) allow you to _call_ that method with variable arguments, but inside the method body they appear collected into a sequence under the name of the argument (otherwise how would you distinguish them?). so you are trying to call a method skipSomething( _: Int, _: Seq[Range]). you can expand a sequence to varargs again for a subsequent call through the special type _* :

def filterYears(toSkip: Range*) = skipSomething(12,toSkip: _*)

best, -sciss-

Erik Osheim

unread,
Jan 12, 2012, 12:12:40 PM1/12/12
to Edmondo Porcu, scala-user
On Thu, Jan 12, 2012 at 06:07:21PM +0100, Edmondo Porcu wrote:
> error: type mismatch;
> found : Range*
> required: Range

Hi Edmondo,

I thin you want to use :_*

For instance:

def foo(ns:Int*) = ns.sum
def bar(ns:Int*) = foo(ns:_*) * 2

Hope this helps!

-- Erik

HamsterofDeath

unread,
Jan 12, 2012, 12:55:43 PM1/12/12
to scala...@googlegroups.com
Am 12.01.2012 18:11, schrieb Sciss:
> varargs (the last parameter with an asterisk) allow you to _call_ that method with variable arguments, but inside the method body they appear collected into a sequence under the name of the argument (otherwise how would you distinguish them?). so you are trying to call a method skipSomething( _: Int, _: Seq[Range]). you can expand a sequence to varargs again for a subsequent call through the special type _* :
>
> def filterYears(toSkip: Range*) = skipSomething(12,toSkip: _*)
and that one goes into the cheat sheet, too
Reply all
Reply to author
Forward
0 new messages