Skip to content

Instantly share code, notes, and snippets.

@marcoslin
Last active April 7, 2021 13:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoslin/184c9c9b2321ad61c0ce8a7f4e81ff50 to your computer and use it in GitHub Desktop.
Save marcoslin/184c9c9b2321ad61c0ce8a7f4e81ff50 to your computer and use it in GitHub Desktop.
Sample Kotlin Script Illustrating how to write a custom Kotlin DSL
#!/usr/bin/env kscript
/**
* Define a Printer class that will prefix the message with given
* symbol and apply a `postfix` to the end of the message.
*
* The methods will be available for the inline function
*/
class Printer(private val postfix: String) {
fun asterix(message: String) {
println("* $message $postfix")
}
fun plus(message: String) {
println("+ $message $postfix")
}
}
/**
* Create a lambda Extention Function to the Printer class
*/
typealias PrinterDSL = Printer.() -> Unit
/**
* Define the actual entry point of the Printer DSL using defined `PrinterDSL`
* typealias as `trailing lambda` of the function
*/
fun printer(postfix: String = "", printerDSL : PrinterDSL): Printer {
return Printer(postfix).apply(printerDSL)
}
// Sample Printer DSL Usage
printer("[debug]") {
asterix("hello")
plus("world")
}
/*
* REFERENCES:
* 1. blog: https://www.grokkingandroid.com/creating-kotlin-dsls/
* 2. kscript: https://github.com/holgerbrandl/kscript
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment