State Hoisting
For your Coda Pizza app, you want the PLACE ORDER button to display the price of a pizza based on its toppings: A plain cheese pizza costs $9.99, and each topping adds $1.00 for the whole pizza or $0.50 for half the pizza. Define a computed property called price on your Pizza class to keep track of this price information.
Listing 27.10 Pricing pizzas (Pizza.kt
)
import com.bignerdranch.android.codapizza.model.ToppingPlacement.* data class Pizza( val toppings: Map<Topping, ToppingPlacement> = emptyMap() ) { val price: Double get() = 9.99 + toppings.asSequence() .sumOf { (_, toppingPlacement) -> when (toppingPlacement) { Left, Right -> 0.5 All -> 1.0 } } ... }
Make sure you import your Left, Right, and All ToppingPlacement ...
Get Android Programming: The Big Nerd Ranch Guide, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.