Skip to content

Instantly share code, notes, and snippets.

@kpradeep12 kpradeep12/Pizza.kt
Last active Jan 26, 2019

Embed
What would you like to do?
This class will demonstrate the kotlin features along with building a Pizza DSL.
enum class Cheese{Light, Normal, Extra;}
enum class Sauce{Marinara, GarlicParmesan, Alfredo}
interface Topping
enum class Veg: Topping {Onion, Tomato, Pepper, Spinach;}
enum class Meat: Topping {Chicken, Pepperoni;}
fun main() =
pizza {
large {
add(Sauce.Alfredo)
add(Cheese.Extra)
toppings {
add(Veg.Tomato, Veg.Onion, Meat.Chicken)
half{
add(Meat.Pepperoni)
}
}
}
}.order()
fun pizza(build: Pizza.() -> Unit): Pizza{
val pizza = Pizza()
pizza.build()
return pizza
}
class Pizza{
var size: String = "Medium"
var sauce: Sauce = Sauce.Marinara
var cheese: Cheese = Cheese.Normal
var toppings: MutableList<Topping> = mutableListOf()
fun large(size: Pizza.() -> Unit){
this.size = "Large"
this.size()
}
fun medium(size: Pizza.() -> Unit){
this.size = "Medium"
this.size()
}
fun toppings(tops: Pizza.() -> Unit) = this.tops()
fun half(side: Pizza.() -> Unit) = this.side()
fun add(sauce: Sauce) : Pizza {
this.sauce = sauce
return this
}
fun add(cheese: Cheese):Unit{
this.cheese = cheese
}
fun add(vararg toppings: Topping) = this.toppings.addAll(toppings)
override fun toString(): String{
return """Pizza [
$size [
Sauce: $sauce Cheese: $cheese
$toppings
]
]"""
}
fun order() = println(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.