Title: Matching Conditions
Slug: matching_conditions
Summary: Matching Conditions Using Scala.
Date: 2017-01-03 12:00
Category: Scala
Tags: Basics
Authors: Chris Albon

If you want to learn more, check out Scala Cookbook and Programming in Scala.

Create A String


In [29]:
// Create some strings
val text1 = "Man"
val text2 = "F"
val text3 = "Dog"

Create A Function That Uses A Match Expression


In [30]:
// Define a function that takes in a string, and matches it
def findGender(word: String) = word match {
    // If any of these words, return "Woman"
    case "Female" | "F" | "Woman" | "Lady" | "Girl" => "Woman"
    // If any of these words, return "Man"
    case "Male" | "M" | "Man" | "Gentleman" | "Boy" => "Man"
    // If anything else, return "Unknown"
    case _ => "Unknown"
}

Apply The Function To The Strings


In [31]:
findGender(text1)


Out[31]:
Man

In [32]:
findGender(text2)


Out[32]:
Woman

In [33]:
findGender(text3)


Out[33]:
Unknown