Chapter 11. DSL construction

 

This chapter covers

  • Building domain-specific languages
  • Using lambdas with receivers
  • Applying the invoke convention
  • Examples of existing Kotlin DSLs

In this chapter, we’ll discuss how you can design expressive and idiomatic APIs for your Kotlin classes through the use of domain-specific languages (DSLs). We’ll explore the differences between traditional and DSL-style APIs, and you’ll see how DSL-style APIs can be applied to a wide variety of practical problems in areas as diverse as database access, HTML generation, testing, writing build scripts, defining Android UI layouts, and many others.

Kotlin DSL design relies on many language features, two of which we haven’t yet fully explored. One of them you saw briefly in chapter 5: lambdas with receivers, which let you create a DSL structure by changing the name-resolution rules in code blocks. The other is new: the invoke convention, which enables more flexibility in combining lambdas and property assignments in DSL code. We’ll study those features in detail in this chapter.

11.1. From APIs to DSLs

11.2. Building structured APIs: lambdas with receivers in DSLs

11.3. More flexible block nesting with the “invoke” convention

11.4. Kotlin DSLs in practice

11.5. Summary

sitemap