Advanced Object-Oriented Programming in Kotlin

May 22 2024 · Kotlin 1.9, Android 14, Kotlin Playground

Lesson 01: Composition & Aggregation

Working with Aggregation

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll build on the e-commerce app while implementing aggregation. Start by opening the Kotlin playground in your browser.

Download the course material from the GitHub link at the side of the video. Copy and paste the code from Aggregation.kts in the Starter folder for Lesson 1. This code is similar to what you had in the previous demo. The only difference is that the products have been put into a list called warehouse and are now printed in the console when you run the app. Run the app to see this in action:

There are 4 kinds of products in the warehouse.
- You have 2 order(s), containing 5 items, at the cost of $2,910.0

Considering the whole purchase transaction again very closely, you’ll realize that the order is independent of the products that make up the items for that order. The products will continue to be in the system even if an order is closed or removed in the app. This is a clear case of aggregation: One object uses the other without imposing any form of control over the object’s lifecycle like composition does.

You’ll still have products with or without an order. The products existed before the order was created and will continue to exist after the order no longer exists.

Create a new order and add two skatingGloves as order items below // TODO: Create a new order:

val order3 = Order()
order3.addOrderItem(OrderItem(warehouse.getValue("skatingGloves"), 2))
orders.add(order3)

Run the app. It behaves just like before:

There are 4 kinds of products in the warehouse.
- You have 3 order(s), containing 7 items, at the cost of $2,934.0

Now, assume you need to delete the new order. Below // TODO: Remove order, remove it from your list of orders:

orders.remove(order3)

After removing the order, the products remain available. In reality, only the quantity of the product will be affected by the state of an order. The product quantity may become 0, but it still exists. This way, it’ll be clear that the shop sells such products, unless it decides to discontinue them.

Run the app. The results are just as expected — you’re left with your previous set of items:

There are 4 kinds of products in the warehouse.
- You have 2 order(s), containing 5 items, at the cost of $2,910.0

That’s all for this demo. Continue to the concluding segment of this lesson.

See forum comments
Cinema mode Download course materials from Github
Previous: Understanding Aggregation Next: Conclusion