Type-Safe Builders

We'll cover the following

A key benefit of using a statically typed language is verifying the soundness of code at compile time. Anytime we deviate from the syntax permitted by the language, the compiler will let us know in no uncertain terms. This prevents a variety of errors from slipping to runtime and thus saves time. When working with DSLs, however, we’re inventing the syntax that’s permitted. The compiler doesn’t have enough details to discern if a particular property access or a method call is legitimate when used within the DSL. This is where type-safe builders come in. Using a special annotation, you can instruct the compiler to keep an eye on the scope of properties and methods. Let’s explore that with a built-in example in Kotlin and then by creating our own custom builder.

HTML builder

My wife says that I’m really good at typing…backspaces. If your typing skills are like mine, you’ll appreciate finding errors sooner than later. Fail fast is a virtue, and compile-time failures can save hours of runtime debugging. We enjoy good compiler support for code we write in languages like Java and Kotlin, but what about creating HTML?

Looking at the built-in type-safe HTML builder in Kotlin is a good way to learn how type safety can be provided with DSLs in general and when working with HTML in particular. Play with the HTML builder at the online try-Kotlin site.

You may create an HTML content like this:

<html>
  <h1>Methods' Behavior<h1>
  <p>This is a sample</p>
</html>

Unless you were highly observant when reading the above HTML content, you may not have noticed that there’s an error in there. More complex HTML content makes finding mistakes extremely hard. Asking someone to debug, just to find a silly mistake that caused the browser to display content poorly, is time consuming, costly for the organization, frustrating, embarrassing, and a disgrace to humanity.

An HTML builder can help in two ways. First, it can help us to write code instead of plain text that’ll generate the HTML content. Second, it can verify, before generation, if the syntax is sound.

Visit the site specific for the Kotlin HTML builder example and replace the entire main() method with the following code:

Get hands-on with 1200+ tech skills courses.