Home > Software engineering >  Scala - is it possible to write HOF that has varargs?
Scala - is it possible to write HOF that has varargs?

Time:12-23

Can I have a higher order function that returns a func(varargs*), for example, (s: String*) => String?

I am trying to do the following:

  def concatKeys(delimiter: String) = {
    def concat(k1: String, k2: String): String = if (k1.isEmpty) k2 else k1   delimiter   k2

    (keys: String*) => keys.foldLeft("")(concat)
  }

But when I use it as expected, the code does not compile:

      val key: String = concatKeys(delimiter)(keyAcc, kv._1)

If I change it to a Traversable:

  def concatKeys(delimiter: String) = {
    def concat(k1: String, k2: String): String = if (k1.isEmpty) k2 else k1   delimiter   k2

    (keys: Traversable[String]) => keys.foldLeft("")(concat)
  }

It naturally compiles:

      val key: String = concatKeys(delimiter)(Set(keyAcc, kv._1))

So, is not possible to return a HOF with varargs? If not, why not?

Thank you all!

CodePudding user response:

Varargs are not a valid type, they are just sugar syntax that is only available on methods, not in functions.
Remember that inside the method body, a vararg parameter is actually just a Seq

So no, you can't.

  • Related