

We are letting the language deal with the default cases without having to repeat ourselves. Pattern matching is possible using Option objects. An Option in Scala can easily be compared to Java’s Optional class.
#Case scala code
Finally, once they have selected their payment method they are redirected to the appropriate payment gateway.įirst lets model the PaymentMethod types sealed trait PaymentMethod object PaymentMethod īy using collect we don't need to provide the default fallback case of returning None plus we get to unwrap all those Some(Order(.)) cases as well as not having to wrap each cases return value in a Some.Īgain this is purely personal opinion but this reduction of noise makes this code much easier to read. In functional languages like Scala, options are structures that either contain a value or not. Once they have placed their order they are taken to a payment selection screen where they can select how they want to pay.
#Case scala how to
This is Recipe 3.7, How to use a Scala match expression like a switch statement. They can pay by various means - Credit Card, Bitcoin and Direct Debit. This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). In Scala when you write i + 1 the compiler first looks for a method called + on the Int. A longer answer is that languages like C++ and Java treat ++ specially, and Scala treats specially, and in an inconsistent way. We have a solution by which a customer can place an order through our system. In Scala, ++ is a valid method, and no method implies assignment. The example I give below has been taken from a real world example but the context has been changed and made bit more trivial and non-specific. This page was last reviewed on Mar 1, 2023. Don't expect any of this to be mind blowing but maybe you're venturing in Scala for the first time or have been tinkering for a while you might find this useful. Match and Case ExamplesUse match with cases to test the value of a variable and return another value. I want to take a look at making effective use of Scala's pattern matching capabilities for a fairly trivial example.
