https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Rob Elliot

03/19/2024, 8:30 PM
Is anyone aware of a code generation tool that can generate a top level function with named and defaulted arguments for a given example of the builder pattern?
I'm imagining a tool that could take this Java class:
Copy code
public class Thing {
    private final boolean turnedOn;
    private final String name;

    public Thing(boolean aBoolean, String aString) {
        this.turnedOn = aBoolean;
        this.name = aString;
    }

    public boolean isTurnedOn() {
        return turnedOn;
    }

    public String getName() {
        return name;
    }

    public static class Builder {

        private boolean turnedOn;
        private String name;

        public void setTurnedOn(boolean turnedOn) {
            this.turnedOn = turnedOn;
        }

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

        public Thing build() {
            return new Thing(turnedOn, name);
        }
    }
}
and generate this Kotlin top level function:
Copy code
fun thing(
  name: String? = null,
  turnedOn: Boolean = false,
): Thing = Thing.Builder()
  .setName(name)
  .setTurnedOn(turnedOn)
  .build()
k

Kirill Grouchnikov

03/19/2024, 8:53 PM
With no annotations on the Java class, its builder and its fields / methods?
r

Rob Elliot

03/19/2024, 8:54 PM
Yup - obviously would be somewhat limited by its ability to recognise conventions
k

Kirill Grouchnikov

03/19/2024, 9:18 PM
That’s not really generation. More like a supercharged code transpiler that can recognize patterns in one language and convert them to idiomatic code in another language.
r

Rob Elliot

03/19/2024, 9:19 PM
It is generation. I'm not talking about converting it. The original java code is still being called.