
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
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.