I started working on the idea of wrapping the KotlinPoet functionality with a functional and expressive Kotlin DSL, utilizing some of the fancy stuff the language introduced.

First of all, I needed to model different code members to data classes and ended up with classes like PackageComposer , ClassComposer and FunctionComposer . To make their initialization awesome, I created top-level functions using…

Backticks

In Kotlin, reserved keywords can still be used as names for functions and properties if they are enclosed with backticks (`). So, I ended up with stuff like the following:

inline fun `fun`(

name: String,

block: FunctionScope.() -> String

) = FunctionComposer().apply { ... }

Using this function is pretty neat.

`fun` ("helloWorld") {

"""

print("Hello World!")

"""

}

To correctly use the above function in a larger scope, like within the declaration of a class or a package, I must pass its result as a parameter to a different function.

To do that and have it look pretty, I used…

Infix Functions

In Kotlin, a single parameter function marked with the infix notation, allows for invoking it without using the dot and for passing data to it without using parenthesis at all.

The drawback is that the receiver of the function must be clearly defined, which means it must precede the function at all times.

Having the whole expressiveness/readability in mind I decided to create top-level immutable properties named compose as the receivers and infix functions named a for handling the output of the aforementioned initialization functions, leading to code like compose a fun . Here’s their source:

val ClassScope.compose = FunctionComposition() infix fun FunctionComposition.a(`fun`: FunctionComposer) = `fun`

ClassScope and other data classes named accordingly, are created for allowing certain functions to be available only within certain blocks of code, i.e. I can declare a function only inside the declaration of a class or a package.