Last active
April 7, 2021 13:32
-
-
Save marcoslin/184c9c9b2321ad61c0ce8a7f4e81ff50 to your computer and use it in GitHub Desktop.
Sample Kotlin Script Illustrating how to write a custom Kotlin DSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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