Scala - Type Patterns



Scala type patterns are used to match against types in pattern matching expressions. So, you can perform type checks and cast operations in a single step. Scala is a statically typed language. Each object has a static type that cannot be changed. For example, a Boolean object can only contain a Boolean expression. So, it is easy to match objects against type patterns.

Type Patterns in Scala

Type patterns are used within pattern matching expressions to match and extract values based on their types. The syntax is -

Syntax

value match {
   // Handle the pattern
   case pattern: Type => 
   // Handle other cases
   case _ => 
}

Example of Scala Type Patterns

Following is the example which shows you how to use type patterns in a pattern matching expression -

object Demo {
   def main(args: Array[String]): Unit = {
      val value: Any = "Scala is awesome!"

      value match {
         case s: String => println(s"String value: $s")
         case i: Int => println(s"Int value: $i")
         case _ => println("Unknown type")
      }
   }
}

Save the above code in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

String value: Scala is awesome!

Here, the value variable is matched against different types using type patterns. The type of value is checked. And so the corresponding case block is executed.

Type Patterns with Collections

You can use type patterns with collections to match elements based on their types. So you can manage different types of elements in a collection efficiently. Following is the example which shows you how to use type patterns with list collection -

Example

object Demo {
   def main(args: Array[String]): Unit = {
      val list: List[Any] = List(1, "Scala", 3.14, true)

      list.foreach {
         case s: String => println(s"String: $s")
         case i: Int => println(s"Integer: $i")
         case d: Double => println(s"Double: $d")
         case b: Boolean => println(s"Boolean: $b")
         case _ => println("Unknown type")
      }
   }
}

Save the above code in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Integer: 1
String: Scala
Double: 3.14
Boolean: true

Type Patterns with Case Classes

You can use type patterns with case classes to match and extract values based on their types. This is used when you work with hierarchies of case classes. Following is the example which shows you how to use type pattern with case classes -

Example

sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Rectangle(width: Double, height: Double) extends Shape

object Demo {
   def main(args: Array[String]): Unit = {
      val shape: Shape = Circle(5.0)

      shape match {
         case Circle(r) => println(s"Circle with radius: $r")
         case Rectangle(w, h) => println(s"Rectangle with width: $w and height: $h")
         case _ => println("Unknown shape")
      }
   }
}

Save the above code in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Circle with radius: 5.0

Type Patterns with Generics

You can use type patterns with generics to match and extract values based on their parameterized types. It is used for managing generic classes and methods.

Example

class Box[T](value: T) {
   def get: T = value
}

object Demo {
   def main(args: Array[String]): Unit = {
      val intBox: Box[Int] = new Box(42)
      val stringBox: Box[String] = new Box("Scala")

      def printBox[T](box: Box[T]): Unit = box match {
         case b: Box[Int] => println(s"Box of Int: ${b.get}")
         case b: Box[String] => println(s"Box of String: ${b.get}")
         case _ => println("Unknown box type")
      }

      printBox(intBox)
      printBox(stringBox)
   }
}

Save the above code in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Box of Int: 42
Box of String: Scala

Here, the printBox method uses type patterns to match and extract values from Box instances based on their parameterized types.

Type Patterns with Sealed Traits

You can use type patterns with sealed traits for pattern matching, as the compiler will warn you if a case is not handled.

Example

sealed trait Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal

object Demo {
   def main(args: Array[String]): Unit = {
      val pet: Animal = Dog("Buddy")

      pet match {
         case Dog(name) => println(s"Dog's name: $name")
         case Cat(name) => println(s"Cat's name: $name")
         case _ => println("Unknown animal")
      }
   }
}

Save the above code in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Dog's name: Buddy

Type Patterns with Option

You can use type patterns with the Option type to handle values that may or may not be present. Following is the example which shows you how to use type pattern with Option -

Example

object Demo {
   def main(args: Array[String]): Unit = {
      val maybeValue: Option[Int] = Some(42)

      maybeValue match {
         case Some(value) => println(s"Value is: $value")
         case None => println("No value")
      }
   }
}

Save the above code in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Value is: 42

Here, the maybeValue variable is matched against the Some and None cases of the Option type.

Notes

  • Type patterns are used to match against types in pattern matching expressions.
  • Typed pattern matches against various types within a single function.
  • These can be used to write more expressive and concise code.
  • You can use type patterns in collections to match elements based on their types.
  • You can use type patterns with sealed traits, generics to match parameterized types, Option types by matching Some and None.
Advertisements