Noix
Noix

Reputation: 60

Can a function receive a tuple with an undertermined number of arguments?

I have a function that can receive a List[tuple3(foo, bar, fooby)] and I realize I would like to use the same function when using a List[tuple4(foo, bar, fooby, foobar)]. I guess I could use a pattern matching on this but that would make a duplication of code. What should I do ?

val tuple3List : List[(Foo, Bar, Fooby)] = List()
val tuple4List : List[(Foo, Bar, Fooby, Foobar)] = List()

myFunc(tuple3List)
myFunc(tuple4List)

def myFunc(tupleList : List[Foo, Bar, Fooby]) = {
}

Upvotes: 2

Views: 56

Answers (2)

Tim
Tim

Reputation: 27356

You can make it generic by using Product but this removes a lot of type information. You can't use overloading because of type erasure issues.

If possible it would be better to use classes rather than tuples and make the 4-element version a subclass of the 3-element version:

trait myTrait { val a: Foo, val b: Bar, val c: Fooby }

case class Three(a: Foo, b: Bar, c: Fooby) extends myTrait
case class Four(a: Foo, b: Bar, c: Fooby, d: Foobar) extends myTrait

def myFunc(list: List[myTrait]) = ???

If you need to use tuples this can be resolved by using a typeclass, but that is quite a heavyweight solution.

Upvotes: 2

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

Tuple3 is a subtype of Product3, Tuple4 is a subtype of Product4...

Product3, Product4... are subtypes of Product.

So you can try

val tuple3List : List[(Foo, Bar, Fooby)] = List()
val tuple4List : List[(Foo, Bar, Fooby, Foobar)] = List()

myFunc(tuple3List)
myFunc(tuple4List)

def myFunc(tupleList : List[Product]) = {
  // Do stuff
}

Also another replacement for "tuple with an undertermined number of arguments" could be shapeless.HList.

Upvotes: 3

Related Questions