Scala
Collections Operations
Functional collection operations: map, filter, fold, groupBy.
By EZ4Code Team
collectionsfunctional
Code
val nums = (1 to 10).toList
// map / filter
val doubled = nums.map(_ * 2)
val evens = nums.filter(_ % 2 == 0)
// fold / reduce
val sum = nums.foldLeft(0)(_ + _)
val product = nums.reduce(_ * _)
// groupBy
val grouped = nums.groupBy(_ % 3)
// Map(0 -> List(3,6,9), 1 -> List(1,4,7,10), 2 -> List(2,5,8))
// flatMap / flatten
val nested = List(List(1,2), List(3,4))
nested.flatten // List(1,2,3,4)
nested.flatMap(_.map(_ * 10)) // List(10,20,30,40)Explanation
Scala collections provide a rich set of higher-order functions. foldLeft takes a seed and accumulates; reduce is a special case without a seed; groupBy partitions by a key function. These are lazy on views and strict on concrete collections.
More Scala Snippets
Pattern Matching
Destructure values and match cases in Scala.
Case Classes
Immutable data classes with auto-generated equals/hashCode/toString.
Traits and Mixins
Compose behaviors using traits with default implementations.
Futures and Async
Asynchronous computation with Future and ExecutionContext.
Implicits (Given/Using in Scala 3)
Type-class derivation and context passing via implicits.
Akka Actors (Pekko)
Message-passing concurrency with the actor model.