Open In App

How does Collect function Work in Scala?

Last Updated : 03 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The collect function in Scala is utilized to extract elements from a collection that satisfy a specified condition defined by a partial function. It can be invoked on any collection type, whether mutable or immutable and always returns a new collection containing the elements that meet the condition specified in the partial function.

Method Signature:

def collect[B](pf: PartialFunction[A, B]): Traversable[B]

1. Partial Function:

The collect function takes a partial function pf as its parameter. This partial function specifies the condition that the elements of the collection must satisfy to be included in the result. It selectively extracts elements from the collection based on the logic defined within the partial function.

syntax:

case patternMatch: DataType => expression

This syntax defines a partial function with a pattern match that specifies the input type (DataType) and the desired output type. It provides clarity and readability to the partial function definition.

Detailed Syntax Example:

Scala
val extractString: PartialFunction[Any, String] = {
  case str: String => str
}


In this example, a partial function named extractString is created. It takes an input of type Any and returns a String. It matches any input that is of type String and returns the same string.

2. Return Type:

The collect function always returns a new collection containing the elements that satisfy the condition specified in the partial function.

Example:

Scala
object Main extends App {
  val mySequence: Seq[Any] = Seq("welcome", "to", 42, "Scala", 99, 88, 77, "Functional Programming !!")
  val extractedStrings: Seq[String] = mySequence.collect {
    case str: String => s"Extracted: $str" // Prefix 'Extracted: ' to each extracted string
  }
}


In this example, the values in the sequence mySequence have been changed to different strings. The extractedStrings variable now holds a new sequence containing the modified string values, with each string prefixed by “Extracted: “.

Examples:

1. Filtering out even numbers from a list:

Scala
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenNumbers = numbers.collect {
  case num if num % 2 == 0 => num
}
println(evenNumbers)
Output: List(2, 4, 6, 8, 10)

2. Extracting strings longer than 5 characters from a list:

Scala
val words = List("apple", "banana", "orange", "kiwi", "strawberry")
val longWords = words.collect {
  case word if word.length > 5 => word
}
println(longWords)
Output: List(banana, orange, strawberry)

3. Converting a list of options to a list of non-empty strings:

Scala
val options = List(Some("hello"), None, Some("world"), Some(""), Some("scala"))
val nonEmptyStrings = options.collect {
  case Some(str) if str.nonEmpty => str
}
println(nonEmptyStrings)
Output: List(hello, world, scala)

Conclusion:

The collect function in Scala provides a convenient way to extract elements from a collection based on specific criteria. Its versatility allows it to be used with both mutable and immutable collection data structures. By utilizing a partial function, we can filter or transform elements according to our requirements, resulting in a new collection containing the desired elements. This functionality enhances the flexibility and ease of use of Scala collections, making data extraction and manipulation more straightforward across various scenarios and data types.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads