简体   繁体   中英

Scala - is it possible to write HOF that has varargs?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM