The best Java idiom I've seem for simulating keyword arguments in constructors is the Builder pattern, described in Effective Java 2nd Edition.

The basic idea is to have a Builder class that has setters (but usually not getters) for the different constructor parameters. There's also a build() method. The Builder class is often a (static) nested class of the class that it's used to build. The outer class's constructor is often private.

The end result looks something like:

public class Foo {
  public static class Builder {
    public Foo build() {
      return new Foo(this);
    }

    public Builder setSize(int size) {
      this.size = size;
      return this;
    }

    public Builder setColor(Color color) {
      this.color = color;
      return this;
    }

    public Builder setName(String name) {
      this.name = name;
      return this;
    }

    // you can set defaults for these here
    private int size;
    private Color color;
    private String name;
  }

  public static Builder builder() {
      return new Builder();
  }

  private Foo(Builder builder) {
    size = builder.size;
    color = builder.color;
    name = builder.name;
  }

  private final int size;
  private final Color color;
  private final String name;

  // The rest of Foo goes here...
}

To create an instance of Foo you then write something like:

Foo foo = Foo.builder()
    .setColor(red)
    .setName("Fred")
    .setSize(42)
    .build();

The main caveats are:

  1. Setting up the pattern is pretty verbose (as you can see). Probably not worth it except for classes you plan on instantiating in many places.
  2. There's no compile-time checking that all of the parameters have been specified exactly once. You can add runtime checks, or you can use this only for optional parameters and make required parameters normal parameters to either Foo or the Builder's constructor. (People generally don't worry about the case where the same parameter is being set multiple times.)

You may also want to check out this blog post (not by me).

Answer from Laurence Gonsalves on Stack Overflow
🌐
GitHub
github.com › tim-group › karg
GitHub - tim-group/karg: Keyword arguments for Java · GitHub
class Example { private static final Keyword<String> GREETING = Keyword.newKeyword(); private static final Keyword<String> NAME = Keyword.newKeyword(); public void greet(KeywordArgument...argArray) { KeywordArguments args = KeywordArguments.of(argArray); String greeting = GREETING.from(args, "Hello"); String name = NAME.from(args, "World"); System.out.println(String.format("%s, %s!", greeting, name)); } public void sayHello() { greet(); } public void sayGoodbye() { greet(GREETING.of("Goodbye"); } public void campItUp() { greet(NAME.of("Sailor"); } } It does a few other things as well - look in the tests for examples.
Starred by 11 users
Forked by 3 users
Languages   Java
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › arguments.html
Passing Information to a Method or a Constructor (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
So using the simple names x or y within the body of the method refers to the parameter, not to the field. To access the field, you must use a qualified name. This will be discussed later in this lesson in the section titled "Using the this Keyword." Primitive arguments, such as an int or a ...
Discussions

Keyword arguments for java? What do you think? - Stack Overflow
In python, the programmer has the option to use keywords arguments in their function calls. For example ... Does any one other than me think that would be a fantasic idea for java? I know that varargs can do a lot, but it doesn't come close to being as useful are keyword arguments. More on stackoverflow.com
🌐 stackoverflow.com
Named Parameters in Java
I'm pro named and default parameters, saying "we don't need that, you just need to use a builder/overload" is exactly like "we don't need lambda expressions, just use an anonymous class". I admit it is just syntax sugar, but it's really sweet sugar. And for me is more intention revealing, and the IDE can really take advantage of it. I think I remember there was a discussion about named parameters at least in constructors for records, and some guy at google said "like 76% of our code are builders, please lets have them" and the answer was "we are going to do that, but we need to really think about the best way" More on reddit.com
🌐 r/java
121
113
November 3, 2022
Can you use a concept similar to keyword args for python in Java to minimize the number of accessor methods? - Stack Overflow
I recently learn that in Python 3, to minimize the number of accessor methods for a class, you can use a dictionaries to essentially just have one set of accessor methods as follows: def __init__(... More on stackoverflow.com
🌐 stackoverflow.com
What is the reason for not allowing named arguments for Java interop? - Language Design - Kotlin Discussions
I have an Android project which calls old java code: ContactsListActivity.startForResultShare( this, STATE_MULTISHARE, -1, -1, R.string.global_title_send ) Far from ideal, I wonder why named arguments are not supported. If I write a small kotlin wrapper around the java call I get them: // Small ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
2
September 13, 2017
Top answer
1 of 16
128

The best Java idiom I've seem for simulating keyword arguments in constructors is the Builder pattern, described in Effective Java 2nd Edition.

The basic idea is to have a Builder class that has setters (but usually not getters) for the different constructor parameters. There's also a build() method. The Builder class is often a (static) nested class of the class that it's used to build. The outer class's constructor is often private.

The end result looks something like:

public class Foo {
  public static class Builder {
    public Foo build() {
      return new Foo(this);
    }

    public Builder setSize(int size) {
      this.size = size;
      return this;
    }

    public Builder setColor(Color color) {
      this.color = color;
      return this;
    }

    public Builder setName(String name) {
      this.name = name;
      return this;
    }

    // you can set defaults for these here
    private int size;
    private Color color;
    private String name;
  }

  public static Builder builder() {
      return new Builder();
  }

  private Foo(Builder builder) {
    size = builder.size;
    color = builder.color;
    name = builder.name;
  }

  private final int size;
  private final Color color;
  private final String name;

  // The rest of Foo goes here...
}

To create an instance of Foo you then write something like:

Foo foo = Foo.builder()
    .setColor(red)
    .setName("Fred")
    .setSize(42)
    .build();

The main caveats are:

  1. Setting up the pattern is pretty verbose (as you can see). Probably not worth it except for classes you plan on instantiating in many places.
  2. There's no compile-time checking that all of the parameters have been specified exactly once. You can add runtime checks, or you can use this only for optional parameters and make required parameters normal parameters to either Foo or the Builder's constructor. (People generally don't worry about the case where the same parameter is being set multiple times.)

You may also want to check out this blog post (not by me).

2 of 16
92

This is worth of mentioning:

Foo foo = new Foo() {{
    color = red;
    name = "Fred";
    size = 42;
}};

the so called double-brace initializer. It is actually an anonymous class with instance initializer.

🌐
Kaashif
kaashif.co.uk › 2023 › 03 › 27 › adding-keyword-arguments-to-java-with-annotation-processing
kaashif.co.uk: Adding keyword arguments to Java with annotation processing
I think that's the best off-the-shelf solution even if it does mean we lose reorderability of arguments. Writing an annotation processor in Java isn't that painful actually. Take a look at the code! https://github.com/kaashif/java-keyword-args/ This is my first time doing anything like this in Java, it was fun to learn about.
🌐
Micro Focus
microfocus.com › documentation › silk-test › 200 › en › silk4j-help-en › GUID-E963C871-5DCE-49DF-9AAC-1B1EA68D6360.html
Keywords
// Java code @Keyword(value="Login", description="Logs in with the given name and password.") public void login(@Argument("UserName") String userName, @Argument("Password") String password, @Argument("Success") OutParameter success) { ... // method implementation } where the keyword logs into the application under test with a given user name and password and returns whether the login was successful.
🌐
Useful
useful.codes › default-and-keyword-arguments-in-java
Default and Keyword Arguments in Java | Useful Codes
In summary, while Java does not support default and keyword arguments in the same way as some other programming languages, it offers robust alternatives through method overloading and design patterns like the builder pattern. These techniques not only enhance the flexibility and readability of your code but also improve the overall developer experience.
🌐
CodingTechRoom
codingtechroom.com › question › understanding-keyword-arguments-in-java
Understanding Keyword Arguments in Java: A Discussion - CodingTechRoom
In Java, the concept of keyword arguments, similar to what is found in languages like Python, does not exist in the same form.
Find elsewhere
🌐
W3Schools
w3schools.com › java › java_methods_param.asp
Java Method Parameters
Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
🌐
Imperial College London
python.pages.doc.ic.ac.uk › java › lessons › java › 07-function › 03-keyword.html
Python for Java Programmers > Keyword arguments | Department of Computing | Imperial College London
Apart from positional arguments, a caller can also use keyword arguments to supply the arguments for these optional parameters without worrying about the positioning of the parameter.
🌐
Wikipedia
en.wikipedia.org › wiki › Named_parameter
Named parameter - Wikipedia
June 25, 2026 - In computer programming, named ... or keyword arguments refer to a computer language's support for function calls to clearly associate each argument with a given parameter within the function call. A function call using named parameters differs from a regular function call in that the arguments are passed by associating each one with a parameter name, instead of providing an ordered list of arguments. For example, consider this Java or C# method ...
🌐
DZone
dzone.com › coding › java › named parameters in java
Named Parameters in Java
September 3, 2014 - The code is still ugly but a bit more readable at the place of the caller. You can even collect static methods into a utility class, or to an interface in case of Java 8 named like with, using, to and so on.
🌐
Baeldung
baeldung.com › home › java › core java › guide to the this java keyword
Guide to the this Java Keyword | Baeldung
January 5, 2024 - We can also use this keyword to return the current class instance from the method. To not duplicate the code, here’s a full practical example of how it’s implemented in the builder design pattern. We also use this to access the outer class instance from within the inner class:
🌐
Jaksa's Blog
jaksa.wordpress.com › 2019 › 10 › 28 › named-parameters-in-java
Named Parameters in Java - Jaksa's Blog - WordPress.com
October 29, 2019 - Java doesn’t natively support named parameters, but we can easily have something like: robot.punch(force(1), speed(100)); Named parameters are very handy when we start having methods with a l…
🌐
Reddit
reddit.com › r/java › named parameters in java
r/java on Reddit: Named Parameters in Java
November 3, 2022 -

I have always wondered why we don't have this in Java and why there has never been a JEP proposing this.

Also Named parameters go hand in glove with default values, similar to how we have Annotation parameters.

So my primary ask is two things,

  1. Do we think Named Parameters in Java is a good idea?

  2. If yes, what's the challenge in adding them in a backward compatible manner.

Edit 1: Someone asked for an example. So here it goes (its oversimplified, not real code obviously)

Consider the below example

public class NamedParametersExample {

    public Long calculateCost(String typeOfPackage, String typeOfCustomer, double additionalDiscount) {
        return calculateCost(typeOfPackage, false, "regular", additionalDiscount);
    }

    public Long calculateCost(String typeOfPackage, String typeOfCustomer) {
        return calculateCost(typeOfPackage, false, "regular", 0.0);
    }

    public Long calculateCost(String typeOfPackage) {
        return calculateCost(typeOfPackage, false, "regular", 0.0);
    }

    public Long calculateCost(String typeOfPackage, boolean wantSameDayDelivery) {
        return calculateCost(typeOfPackage, wantSameDayDelivery, "regular", 0.0);
    }

    public Long calculateCost(String typeOfPackage, boolean wantSameDayDelivery, double additionalDiscount) {
        return calculateCost(typeOfPackage, wantSameDayDelivery, "regular", additionalDiscount);
    }

    public Long calculateCost(String typeOfPackage, boolean wantSameDayDelivery, String typeOfCustomer, double additionalDiscount) {
        //Implementation
    }
}

If you write the same in Kotlin, it gets simplified to,

class NamedParametersKotlin {

    fun calculateCost(
        typeOfPackage: String,
        wantSameDayDelivery: Boolean = false,
        typeOfCustomer: String = "regular",
        additionalDiscount: Double = 0.0
    ): Long {
        //Real code
        return 0L
    }
 }

Which can then be invoked like,

fun callerExample() {
        calculateCost(typeOfPackage = "Grocery", wantSameDayDelivery = true)
        calculateCost(typeOfPackage = "HighValue", additionalDiscount = 0.3)
        calculateCost(typeOfPackage = "Subscription", additionalDiscount = 0.3, typeOfCustomer = "subcriber")
    }

Edit 2: Stop reading this question as I am complaining about not having Named Parameters in Java or that I am saying "Kotlin Good, Java bad". I am genuinely curious the advantages/disadvantages of adding Named Parameters in Java. Also please don't reply, "just overload the method". That point of this question is not to know how we can continue to function without Named parameters.

Edit 3: Thanks everyone for your insightful comments. This is exactly what I was looking for and I now have good enough amount of material to read and follow up this weekend. :)

Top answer
1 of 4
7

No there is no kwargs in java. Instead you can something similar to your function by using java varargs to save them as java properties.

You do you can something like this:

useKwargs("param1=value1","param2=value2");

Example code:

public void useKwargs(String... parameters) {

        Properties properties = new Properties();

        for (String param : parameters) {
            String[] pair = parseKeyValue(param);

            if (pair != null) {
                properties.setProperty(pair[0], pair[1]);
            }

        }

        doSomething(properties);
    }

    public void doSomething(Properties properties) {
        /**
         * Do something using using parameters specified in the properties
         */

    }

    private static String[] parseKeyValue(String token) {
        if (token == null || token.equals("")) {
            return null;
        }

        token = token.trim();

        int index = token.indexOf("=");

        if (index == -1) {
            return new String[] { token.trim(), "" };
        } else {
            return new String[] { token.substring(0, index).trim(),
                    token.substring(index + 1).trim() };
        }

    }
2 of 4
5

Use that pattern if it suits and it fits best but it really should be an exception to the rule in Java - it will probably not be appropriate.

Best practice in Java is to use getter and setter methods for each variable. Yes it's more code - so what - if your lazy get your IDE to auto-generate them. It's there for a very good reason. Many good reasons. Some are;

  • Promotes private variables
  • Defines an external interface to other classes allowing the class to control what and how to set or get variables
  • Promotes good coding practice by establishing a standard way to deal with object variables

The problem you'll encounter here by porting this pattern over is due to typing. Python is dynamically typed and Java is statically typed. So, in order to use the same pattern in Java, you will have to store the values in something like a string/object array and then return them like that as an object or as a String. then you'll have to convert them sometime later. Maybe if your 'properties' were all strings it would be okay. There are exceptions to the rule, but you need to know all of the rules in order to break them well. If they are different types (String, int, CustomObject etc.) don't use the same pattern you use in Python.

🌐
Tbee
tbee.org › 2021 › 12 › 25 › java-named-parameters-revisited
Java named parameters revisited – TbeeRNot
December 25, 2021 - Parameters with defaults become optional, all other parameters must be present in the named arguments. Named parameters require that methods have the method names present in the class files. This is optional for javac.
🌐
Imperial College London
python.pages.doc.ic.ac.uk › java › lessons › java › 07-function › 07-arbitrary.html
Python for Java Programmers > Arbitrary number of keyword arguments | Department of Computing | Imperial College London
def customise_page(**kwargs): parse_args(kwargs) def parse_args(options): for key, value in options.items(): if key == "background": set_background(value) elif key == "width": set_width(value) elif key == "avatar": set_avatar(value) else: print(f"Unknown keyword {key}.") return customise_page(background="red", width=500, avatar="selfie.jpg")
🌐
Scribd
scribd.com › presentation › 382639590 › This-Keyword-in-Java
Understanding 'this' Keyword in Java | PDF | Method (Computer Programming) | Constructor (Object Oriented Programming)
It allows accessing members of the current object from within methods or constructors. The this keyword can be used to refer to current class instance variables, invoke constructors, call methods implicitly, pass the current object as an argument...
Rating: 5 ​ - ​ 2 votes
🌐
Kotlin Discussions
discuss.kotlinlang.org › language design
What is the reason for not allowing named arguments for Java interop? - Language Design - Kotlin Discussions
September 13, 2017 - I have an Android project which calls old java code: ContactsListActivity.startForResultShare( this, STATE_MULTISHARE, -1, -1, R.string.global_title_send ) Far from ideal, I wonder why named arguments are not supported. If I write a small kotlin wrapper around the java call I get them: // Small ...