3 ms·
What's the distinguishing difference between a regular library and an embedded DSL?
by runeks 3y ago
What's the distinguishing difference between a regular library and an embedded DSL?
- jillesvangurp 3y agoThe difference is making an effort to expose the features of the library via a syntactically friendly way. Most Kotlin libraries indeed have nice APIs that are effectively mini DSLs. If you need an example, Kotlin uses a nice internal DSL for HTML where you write things like Div { P { +"Hello world" } } This is valid Kotlin that happens to construct a dom tree. There is no magic going on here; just usage of a few syntax features of the language. Div and p here are normal functions that take a receiver block as the last parameter that receive an instance of the element they are creating. The + in front of the string is function with a header like this in the implementation of that element. operator fun String.unaryPlus() The same code in Java would be a lot messier because of the lack of syntactical support for this. You basically end up with a lot of method chaining, semicolumns and their convoluted lamda syntax. The article has a few examples that would look a lot cleaner if you'd rewrite them in Kotlin.