Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to use Scala matching pattern to check the contents of an object

Shulou Source: shulou.com Published: 2022-05-31 21:24:36 09月20日 Update

This article mainly explains "how to use Scala matching pattern to check the content of an object". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Scala matching pattern to check the content of an object".

Let's try a deep match to check the contents of the object in our pattern matching.

/ / code-examples/Rounding/match-deep-script.scala

Case class Person (name: String, age:Int)

Val alice = new Person ("Alice", 25)

Val bob = new Person ("Bob", 32)

Val charlie = newPerson ("Charlie", 32)

For (person println ("HiAlice!")

Case Person ("Bob", 32) = > println ("Hi Bob!")

Case Person (name, age) = > println ("Who are you," + age + "year-old person named" + name + "?")

}

}

As we can see from the output of the above example, poor Charlie is ignored:

?

one

two

3 HiAlice!

Hi Bob!

Who are you, 32 year-old person namedCharlie?

We define a case class, a special type of class, and now we just need to know that a case class allows the construction of refined simple objects, as well as some predefined methods. Then, our pattern matching looks for Alice and Bob by checking the value of the Person case class passed in. Charlie was not captured until the last hungry case; although he was the same age as Bob, we also checked the name attribute.

As we will see later, this type of pattern matching can be very useful when working with Actor. Case classes are often sent to Actor as messages, and deep pattern matching of the contents of an object is a convenient way to "analyze" these messages.

Thank you for reading, the above is the content of "how to use Scala matching pattern to check the content of the object". After the study of this article, I believe you have a deeper understanding of how to use Scala matching pattern to check the content of the object, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Content pattern object inspection learning message depth type special hungry example at the same time name attribute regular meeting age train of thought situation article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple OPPO Reno Docker Redmi Linux