Skip to content

Instantly share code, notes, and snippets.

@lekaha
Created June 29, 2018 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lekaha/19147d6a6783889c17a05c1b37fef164 to your computer and use it in GitHub Desktop.
Save lekaha/19147d6a6783889c17a05c1b37fef164 to your computer and use it in GitHub Desktop.
Example of using DSL marker annotation
@DslMarker
annotation class ReceiptDsl
data class Amount(val total: Int, val tax: Float)
data class Receipt(val title: String, val date: String, val staffName: String, val amount: Amount)
@ReceiptDsl
class AmountBuilder {
var total: Int = 0
var tax: Float = .0f
fun build() = Amount(total, tax)
}
@ReceiptDsl
class ReceiptBuilder {
var title: String = ""
var date: String = ""
var staffName: String = ""
private var amount: Amount? = null
fun amount(λ: AmountBuilder.() -> Unit) = AmountBuilder().apply(λ).build()
fun build() = Receipt(title, date, staffName, amount ?: amount{})
}
fun receipt(λ: ReceiptBuilder.() -> Unit) = ReceiptBuilder().apply(λ).build()
fun main(args: Array<String>) {
val john = receipt {
title = "Beef noodle"
date = "2018/6/28"
staffName = "John"
amount {
total = 990
tax = 9.9F
}
}
receipt {
title = "Beef rice"
date = "2018/6/28"
staffName = "Mary"
amount {
total = 980
tax = 9.9F
}
}
println(john)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment