Scala Project: Bill Splitter
A bill splitter is a program that totals a list of item prices, adds a tip, and divides the cost evenly between friends. This project builds one from a List, a def with a default value, and formatted money output.
Each price prints as money
The foreach call visits every price in the list. Each price prints with two decimal places.
@main def main(): Unit =
val prices = List(18.0, 12.0, 6.0, 4.0)
prices.foreach(price => println(f"Item price: $price%.2f"))A def adds the tip
The def totals the prices and adds a tip of the given percentage. A 10 percent tip on 40 gives a total of 44.
def totalWithTip(prices: List[Double], tipPercent: Double = 10.0): Double =
val subtotal = prices.sum
subtotal + subtotal * tipPercent / 100
@main def main(): Unit =
val prices = List(18.0, 12.0, 6.0, 4.0)
println(f"Total: ${totalWithTip(prices)}%.2f")Example
def totalWithTip(prices: List[Double], tipPercent: Double = 10.0): Double =
val subtotal = prices.sum
subtotal + subtotal * tipPercent / 100
@main def main(): Unit =
val items = List(("Pizza", 18.0), ("Pasta", 12.0), ("Cake", 6.0), ("Coffee", 4.0))
items.foreach(item => println(f"${item._1}: ${item._2}%.2f"))
val prices = items.map(item => item._2)
val total = totalWithTip(prices)
val friends = 4
val each = total / friends
println(f"Total with tip: $total%.2f")
println(f"Each of $friends friends pays: $each%.2f")Key points
- Prices: the item prices are held in a List of Double values.
- Total def: a def adds up the prices and adds a tip based on a percentage.
- Default argument: the tip percentage has a default value, so a call can leave it out.
- foreach: runs a printing step once for each item in a list.
- Money format: f-interpolation with %.2f prints a price with exactly two decimal places.
- Share: dividing the total by the number of friends gives the amount each friend pays.
In this example, the items list pairs each food name with its price, and foreach prints one formatted line per item. The map call pulls out just the prices, totalWithTip adds the default 10 percent tip to give 44.00, and dividing by 4 friends gives 11.00 each.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
In the project, what tip does totalWithTip use when the call passes no tip percentage?