1

Python 3 will allow iterable unpacking such as:

>>> def foo(a, b, c): return a + b + c
... 
>>> s1 = "one"
>>> s2 = ("two", "three")
>>> foo(s1, *s2)
'onetwothree'

I have seen How to apply a function to a tuple? and scala tuple unpacking but am having trouble emulating this in Scala (2.13):

scala> def foo(a: String, b: String, c: String): String = a + b + c
foo: (a: String, b: String, c: String)String

scala> val s1 = "one"
s1: String = one

scala> val s2 = Seq("two", "three")
s2: Seq[String] = List(two, three)

How can I mimic foo(s1, s2: _*)?

The closest I've gotten is with this combination of uncurried/curried, but frankly I'm not really understanding why this last attempt doesn't work:

scala> Function.uncurried((foo _).curried(s1))
res17: (String, String) => String = scala.Function$$$Lambda$897/0x0000000801070840@145f1f97

scala> Function.uncurried((foo _).curried(s1))(s2(0), s2(1))
res19: String = onetwothree

scala> Function.uncurried((foo _).curried(s1))(s2: _*)
                                              ^
       error: not enough arguments for method apply: (v1: String, v2: String)String in trait Function2.
       Unspecified value parameter v2.
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • No, that won't work. You would need to edit the question signature or derive other one for the first one, but frankly I won't bother with that, just unpack the tuple and call the function. – Luis Miguel Mejía Suárez Mar 29 '20 at 18:57

1 Answers1

3

If s2 were a tuple then things would be pretty straight forward.

def foo(a:String, b:String, c:String) :String = a + b + c
val s1 = "one"

val s2 = ("two", "three")
(foo(s1, _, _)).tupled(s2)  //res0: String = onetwothree

But as a Seq() I think the best you can do is a wrapper that unpacks the elements for you.

def foox(ss:String*) :String = foo(ss(0), ss(1), ss(2))  //danger

val s3 = Seq("two", "three")
foox(s1 +: s3 :_*)  //res1: String = onetwothree

There's no easy way (that I know of) to transition a non-varargs method to a varargs method/function.

jwvh
  • 50,871
  • 7
  • 38
  • 64