Created
June 29, 2018 01:03
-
-
Save lekaha/19147d6a6783889c17a05c1b37fef164 to your computer and use it in GitHub Desktop.
Example of using DSL marker annotation
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
@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