0

I am a newbie in Scala and am trying to understand partially applied functions. I can implement simple examples like when function takes two integers as input. But I wanted to combine variable number of arguments with partially applied functions without using currying. I haven't studied much on currying so am not using that totally. This is all I could come up with which doesn't work.

def func1(a:Int, b:Int*) {
   println(a)
}

val func2 = func1(2,_) // error - type mismatch;
                       // found   : Seq[Int]
                       // required: Int

Can anyone tell how to preserve the varargs such that I can still call func2 like func2(2,3,4)? I have seen examples using currying but haven't seen anyone without that

It's not duplicate of Error with varargs for function-objects in Scala? because the mentioned question asks for implementing varargs in function literals and my question is totally different. At first, I am using method (not function literals). Secondly, I am asking for implementing partially applied functions with varargs (which is nothing in relation to the mentioned question)

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Dhruv
  • 117
  • 11
  • *"At first, I am using method (not function literals)"* `func1(2,_)` is a function literal – Dmytro Mitin Mar 15 '23 at 16:45
  • I thought a syntax of `(a:Int) => {do something}` means a function literal. Can you give some reference to study? I am a newbie and don't know much – Dhruv Mar 15 '23 at 17:42
  • `foo(_)` is a shorthand for `a => foo(a)`. https://stackoverflow.com/questions/8000903/ https://stackoverflow.com/questions/2529184/ https://stackoverflow.com/questions/4839537/ https://stackoverflow.com/questions/155609/ https://stackoverflow.com/questions/9440722/ Have you already read [Programming in Scala](https://www.artima.com/shop/programming_in_scala_5ed)? https://docs.scala-lang.org/books.html – Dmytro Mitin Mar 15 '23 at 18:26
  • You could define `val func2 = func1(2, (_: Seq[Int]): _*)` and apply it like `func2(Seq(2,3,4))`. For `def func1(a:Int, b:Int*)` what type would you expect that `func1(2,_)` has? There is type `Int => Unit` aka `Function1[Int, Unit]` and type `Seq[Int] => Unit` aka `Function1[Seq[Int], Unit]` but there are no really variadic functions, only variadic methods. Also https://stackoverflow.com/questions/56933386/how-to-reference-a-function-that-takes-varargs https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#facilities-for-abstracting-over-arity – Dmytro Mitin Mar 15 '23 at 18:47
  • The only useful line I got from the mention question is `val f = sum _` from which I inferred on how to call my own function using `func1(2,(_:scala.collection.immutable.Seq[Int]):_*)`. Don't know whether this is it for my question or not? – Dhruv Mar 15 '23 at 18:51
  • See my previous comment – Dmytro Mitin Mar 15 '23 at 18:53

0 Answers0