Overloading vararg method for Iterable


#1

Hi,

I’m working on a project where we’re using vararg methods a lot. The problem is, whenever we want to use an existing Seq for arguments, we must use this ugly :_* syntax. We could make an overload that accepts Seq, but since vararg methods have the same signature as methods accepting Seq, we can’t actually. So we’ve been using :_* everywhere. But recently, a colleague of mine has come up with a workaround: since Seq is deriving from Iterable, we can overload the method for it, so it can be called with Seq without the :_*.

def foo(args: T*) = foo(args)
def foo(args: Iterable[T]) = ???

foo(1, 2, 3) // works
foo(Seq(1, 2, 3)) // also works

This sounds like an obvious thing to do, but I haven’t seen it used anywhere else. Is something wrong with this solution? Is there anything that can go wrong with this that makes people stay away from it? Or is it just that not many people feel the need to get rid of that :_*?


#2

Iterable is very generic - it could be Seq, Set, Stream etc.

I usually use something like:

def foo(args: Seq[T]) = ???

def foo(arg: T, args: T*) = foo(arg +: args)

If you need a zero-argument version, you can also add:

def foo() = foo(Seq.empty[T])