Building the book DSL – step by step
We’ll build our DSL from the inside out, starting with the nested component functions and ending with the top-level book function – the builder classes.
The core idea behind many Kotlin DSLs is the Type-Safe Builder pattern. Builders are helper classes that accumulate data and then create the final immutable object. Each builder will expose properties and methods that correspond to the DSL syntax we want to achieve.
We’ll need builders for Book, Author (within a list of authors), and Chapter (within a list of chapters).
AuthorBuilder
This builder will help construct an Author object.
Add the following code:
class AuthorBuilder {
var name: String = ""
var country: String = ""
fun build(): Author {
if (name.isBlank()) throw IllegalArgumentException("Author name cannot be blank.")
if (country.isBlank()) throw IllegalArgumentException("...