Skip to content

Instantly share code, notes, and snippets.

@joost-klitsie
Last active July 22, 2023 11:54
Show Gist options
  • Save joost-klitsie/ea6d1c94a103f02cab7f3dd937a5f121 to your computer and use it in GitHub Desktop.
Save joost-klitsie/ea6d1c94a103f02cab7f3dd937a5f121 to your computer and use it in GitHub Desktop.
Kotlin Builder
public static final void printText(@NotNull SimpleClass $this$printText) {
Intrinsics.checkNotNullParameter($this$printText, "$this$printText");
String var1 = $this$printText.getText();
System.out.println(var1);
}
class SimpleClass private constructor(val text: String?, val count: Int) {
class Builder(var text: String? = null, var count: Int? = null) {
fun build() = SimpleClass(text = text, count = count)
}
}
fun SimpleClass.printText() {
println(text)
}
fun main() {
val simpleClass = SimpleClass.Builder().build()
simpleClass.printText()
}
fun buildSimpleClass(
configure: SimpleClass.Builder.() -> Unit
): SimpleClass {
val builder = SimpleClass.Builder()
builder.configure()
return builder.build()
}
public class SimpleClass {
public final String text;
public final int count;
private SimpleClass(String text, int count) {
this.text = text;
this.count = count;
}
public static class Builder {
private String text;
private int count;
public Builder setText(String text) {
this.text = text;
return this;
}
public Builder setCount(int count) {
this.count = count;
return this;
}
}
}
SimpleClass.Builder builder = new SimpleClass.Builder();
builder.setCount(1).setText("Some text");
SimpleClass result = builder.build();
val simpleClass = buildSimpleClass {
text = "Some text"
count = 4
}
simpleClass.printText() // Will print “Some text”
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment