Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Builder with constructor parameters #3

Open
Frontrider opened this issue Sep 25, 2023 · 0 comments
Open

Builder with constructor parameters #3

Frontrider opened this issue Sep 25, 2023 · 0 comments

Comments

@Frontrider
Copy link

Frontrider commented Sep 25, 2023

I'm opening this issue, because your code of conduct says that I should before opening a PR. I'm working on some tooling to make it easier for me to create dsl-s, and this code was almost perfect.

My only addition would be this:

@GenerateBuilder
class Role(
    @GenerateBuilder.ConstructorValue
    val name: String,
    val users: Map<String, User>
)

An extra annotation that makes the builder have a constructor parameter, so I can set the field before I hand it over to the user of the dsl. (I can restrict access to it as needed)

This is the generated code:

public class RoleBuilder(
    name: String,
) {
    private var name: String?

    private var users: MutableMap<String, User> = mutableMapOf()
    init {
        this.name = name
    }

    public constructor(o: Role) : this(o.name) {
        this.name = o.name
        this.users = o.users.toMutableMap()
    }

    public fun users(users: Map<String, User>): RoleBuilder {
        this.users = users.toMutableMap()
        return this
    }

    public fun putUsers(k: String, v: User): RoleBuilder {
        this.users.put(k, v)
        return this
    }

    public fun putAllUsers(users: Map<String, User>): RoleBuilder {
        this.users.putAll(users)
        return this
    }

    public fun build(): Role = Role(name = name!!, users = users)
}

This was a quick change that does not break any existing functionality, although has that artifact where the field is still marked as nullable so that needs to be handled in the builder.

I'll accept if you disagree with this change. In that case I'm forking it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant