Skip to content

Add safe builders#90

Draft
kyay10 wants to merge 1 commit intoF43nd1r:masterfrom
kyay10:safety
Draft

Add safe builders#90
kyay10 wants to merge 1 commit intoF43nd1r:masterfrom
kyay10:safety

Conversation

@kyay10
Copy link
Contributor

@kyay10 kyay10 commented Jan 23, 2026

Fixes #86, #87

An unsafe version of the API is exposed by using XBuilderImpl in case someone needs it. Technically, the builder style withX methods can be made safe as well, but I feel they're unlikely to be used in Kotlin, so I've omitted them. AssignOnce safety is there to catch simple mistakes, but it can be circumvented incredibly easily with something as simple as if (true) foo = x; foo = x. It also currently doesn't do anything for nested dsls (e.g. PersonBuilder.address), but maybe it could in the future using error deprecation or an opt-in annotation.
Another point of contention is that types are made nullable no matter what. That's annoying because someone might assign a field, and immediately try to access it, only to have it be nullable. This could be improved in the future, but it'd have to change the logic in BuilderImpl classes significantly, and it'd mean that the unsafe version wouldn't have the same semantics as AutoDsl builders do right now (e.g. accessing a required parameter wouldn't give you null if it isn't filled yet).

The approach in this PR is incredibly nice and easy to consume in Kotlin (it's my personal favourite). There is an alternative approach that uses type parameters. It would be usable from Java safely (which the current one isn't, with Java consumers having to fall back to the unsafe API), while being slightly more annoying in Kotlin (due to all the type parameters).

@kyay10 kyay10 marked this pull request as draft January 31, 2026 22:20
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

Successfully merging this pull request may close these issues.

Compile-time verification of required parameters using contracts

1 participant