Search⌘ K

Solution Review: Color Wheel

Explore the Scala color wheel solution by understanding how to use match expressions for conditional logic. Learn to implement control structures like case matching effectively to handle different input scenarios and enhance your Scala programming skills.

We'll cover the following...

Task

In this challenge, you were provided a primary color and you had to match it to its complementary secondary color.

Solution

Let’s go over the solution step-by-step.

  • The first thing you had to figure out is that this problem requires a match expression.

  • Next, you had to figure out the number of cases the match expression would require to cover all the possible scenarios. We had one case for each primary color along with a default case if the input was anything but a primary color.

case "blue" => print("orange")
case "yellow" => print("purple")
case "red" => print("green")
case _ => print("not a primary color")

You can find the complete solution below:

You were required to write the code from line 3 to line 8.

Scala
var testVariable = "red"
testVariable match {
case "blue" => print("orange")
case "yellow" => print("purple")
case "red" => print("green")
case _ => print("not a primary color")
}

In the next lesson, we will complete our discussion on control structures with types of patterns.