0

When implementing a java function to accept arbitrary number of arguments, what will be the right way of doing that?

In python, i will do

def sumUp(*args):
      res = 0
      for arg in args:
         res = res + arg
      return res

sumUp(12,1)  # return 13
sumUp(12,8,6) # return 26

Is there something in java closely equivalent to this without having to pass in a list argument? And what about **kwargs?

Godswill
  • 35
  • 4
  • Either varargs as [explained by @shmosel](https://stackoverflow.com/a/74956903/4216641) or a [`List`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html) of something (although the later is a little bit more syntax-heavy). – Turing85 Dec 29 '22 at 23:27

1 Answers1

2

You can use varargs if they're all the same type:

int sumUp(int... args) {
    int res = 0;
    for (int arg : args)
        res += arg;
    return res;
}
shmosel
  • 49,289
  • 6
  • 73
  • 138