Exercise: Pizza factory
Your task is to define a companion object in the Pizza
class that will contain factory functions for creating pizzas. The functions should be named hawaiian
and margherita
and should return pizzas with the following toppings:
- Hawaiian: ham, pineapple
- Margherita: tomato, mozzarella
class Pizza(
val toppings: List<String>,
) {
// Class body
}
In the starting code, there is an empty class body with a comment. I added it because otherwise, people doing the exercise often got confused, and instead of in the class body, they defined the companion object in the constructor.
The following code should work:
val hawaiian = Pizza.hawaiian()
println(hawaiian.toppings) // [ham, pineapple]
val margherita = Pizza.margherita()
println(margherita.toppings) // [tomato, mozzarella]
This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in essentials/objects/Pizza.kt. You can find there starting code, example usage and unit tests.
Hint: To create a list of strings, you can use the listOf
function. For example, listOf("a", "b", "c")
creates a list with three elements: "a"
, "b"
, and "c"
.
Once you are done with the exercise, you can check your solution here.
import org.junit.Test
import kotlin.test.assertEquals
class Pizza(
val toppings: List<String>,
) {
// Class body
}
fun main() {
val hawaiian = Pizza.hawaiian()
println(hawaiian.toppings) // [ham, pineapple]
val margherita = Pizza.margherita()
println(margherita.toppings) // [tomato, mozzarella]
}
class PizzaTest {
@Test
fun testHawaiian() {
val expected = listOf("ham", "pineapple")
assertEquals(expected, Pizza.hawaiian().toppings)
}
@Test
fun testMargherita() {
val expected = listOf("tomato", "mozzarella")
assertEquals(expected, Pizza.margherita().toppings)
}
}
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.