#scala
100 snippets tagged with #scala
Scala Hello World Application
Create a basic Scala application with main method, string interpolation, and val/var basics.
Best for: Getting started with Scala
Pattern Matching Fundamentals
Use Scala pattern matching with guards, type patterns, tuple patterns, and nested extractors.
Best for: Control flow with pattern matching
Case Classes and Objects
Define immutable data with case classes: copy, equality, destructuring, and companion objects.
Best for: Domain modeling with immutable data
Collections Map Filter Fold Operations
Master Scala collections: map, flatMap, filter, fold, groupBy, partition, and zip operations.
Best for: Data transformation and aggregation
Option Either and Try Error Handling
Handle errors functionally with Option, Either, and Try: map, flatMap, recover, and for-comprehensions.
Best for: Null-safe programming with Option
Traits and Mixin Composition
Compose behavior with Scala traits: stackable modifications, self-types, and diamond resolution.
Best for: Composable behavior via mixins
Implicits and Givens Context Parameters
Use Scala 3 givens and using clauses for type classes, context parameters, and implicit conversions.
Best for: Type class pattern for ad-hoc polymorphism
For-Comprehensions and Monadic Composition
Use for-comprehensions with Option, Either, Future, and custom monads for elegant composition.
Best for: Chaining optional computations
Higher-Order Functions and Closures
Write and use higher-order functions: function literals, closures, currying, and partial application.
Best for: Building custom control structures
Generics Variance and Type Bounds
Use Scala generics with covariance, contravariance, upper/lower bounds, and context bounds.
Best for: Type-safe container libraries
Futures and Async Programming
Use Scala Futures for async operations: map, flatMap, recover, sequence, and race patterns.
Best for: Asynchronous API calls
Enums and Algebraic Data Types
Define enums and ADTs in Scala 3: parameterized enums, sealed hierarchies, and exhaustive matching.
Best for: Domain modeling with algebraic data types
Extension Methods and Type Enrichment
Add new methods to existing types with Scala 3 extension methods and type enrichment patterns.
Best for: Adding utility methods to standard types
Parallel Processing with Collections
Process data in parallel using parallel collections, Future.traverse, and batched execution.
Best for: Speeding up CPU-bound operations
Type Class Pattern Implementation
Implement the type class pattern in Scala 3: define, provide instances, and use with extension methods.
Best for: Ad-hoc polymorphism without inheritance
Akka Actor System Basics
Build concurrent applications with Akka actors: message passing, behavior switching, and supervision.
Best for: Concurrent message-passing systems
Cats Effect IO Monad Basics
Use Cats Effect IO for pure functional effects: sequencing, error handling, resource management.
Best for: Pure functional effect management
ZIO Effect System Basics
Build programs with ZIO: effects, error handling, layers, and concurrent operations.
Best for: Typed error handling with ZIO
Apache Spark DataFrame Operations
Process big data with Spark DataFrames: read, filter, aggregate, join, and write operations.
Best for: Big data processing with Spark
Sealed Traits and Type Hierarchies
Model domain hierarchies with sealed traits for exhaustive pattern matching and type safety.
Best for: Payment method modeling
Map and HashMap Operations
Work with Scala Maps: create, update, merge, transform, and use default values.
Best for: Configuration management
String Processing and Regex
Process strings with Scala regex, interpolation, pattern matching extractors, and common operations.
Best for: Text parsing and extraction
File I/O Read and Write Operations
Read and write files in Scala: text files, CSV parsing, JSON handling, and resource management.
Best for: Reading configuration files
Lazy Evaluation and LazyList Streams
Use lazy evaluation with LazyList for infinite sequences, memoization, and deferred computation.
Best for: Infinite sequence generation
HTTP Client with sttp
Make HTTP requests with sttp: GET, POST, headers, JSON bodies, and async backends.
Best for: REST API integration
Play Framework REST Controller
Build REST APIs with Play Framework: routes, JSON serialization, async actions, and error handling.
Best for: REST API development
Unit Testing with ScalaTest
Write unit tests with ScalaTest: FunSuite, FlatSpec, matchers, mocking, and async testing.
Best for: Unit testing Scala code
Opaque Types for Type Safety
Use Scala 3 opaque types to create zero-cost type wrappers for domain modeling.
Best for: Domain-driven type safety
Given Imports and Exports
Manage given instances with Scala 3 import syntax: selective imports, exports, and priorities.
Best for: Organizing type class instances
Concurrent Programming with Atomic Refs
Use atomic references and concurrent data structures for thread-safe state management.
Best for: Lock-free data structures
Context Functions and Capability Pattern
Use Scala 3 context functions for dependency injection, capability passing, and builder DSLs.
Best for: Dependency injection without frameworks
Recursive Data Structures and Algorithms
Implement recursive data structures: binary trees, linked lists, and tree traversal algorithms.
Best for: Implementing custom data structures
JSON Parsing with Circe
Parse and generate JSON with Circe: codecs, custom encoders/decoders, and optics.
Best for: REST API JSON handling
Spark RDD Transformations and Actions
Process distributed data with Spark RDDs: map, reduce, aggregate, and pair RDD operations.
Best for: Distributed data processing
Advanced Pattern Matching Techniques
Master advanced patterns: custom extractors, unapply, variable binding, and deep matching.
Best for: Custom domain extractors
Type-Level Programming Basics
Explore Scala 3 type-level programming: match types, singleton types, and type lambdas.
Best for: Type-safe library APIs
Database Access with Doobie
Query databases with Doobie: SQL interpolation, type-safe queries, transactions, and streaming.
Best for: Type-safe database queries
Tuples and Product Types
Work with Scala 3 tuples: named tuples, tuple operations, conversions, and generic programming.
Best for: Returning multiple values from functions
Tail Recursion with @tailrec
Write stack-safe recursive functions using @tailrec annotation and accumulator patterns.
Best for: Stack-safe recursive algorithms
Implicit Conversions in Scala 3
Use Scala 3 Conversion type class for safe implicit conversions and interop patterns.
Best for: Unit conversion libraries
Cats Monad Transformers
Use Cats monad transformers: EitherT, OptionT, and StateT for composable effect stacks.
Best for: Composable error handling stacks
Collection Views for Lazy Operations
Use collection views for efficient lazy transformations: avoid intermediate collections and improve performance.
Best for: Memory-efficient data processing
Property-Based Testing with ScalaCheck
Write property-based tests with ScalaCheck: generators, properties, shrinking, and custom Arbitrary.
Best for: Exhaustive testing with random inputs
DSL Builder Pattern
Create type-safe domain-specific languages with Scala's builder pattern using apply and infix notation.
Best for: Type-safe query builders
Error Accumulation with Validated
Accumulate multiple validation errors instead of failing fast using Cats Validated and custom validators.
Best for: Form validation with all errors
Union and Intersection Types
Use Scala 3 union and intersection types for flexible and precise type definitions.
Best for: Flexible function parameters
Type Class Derivation with Mirrors
Derive type class instances automatically using Scala 3 Mirrors and inline metaprogramming.
Best for: Automatic codec generation
Inline and Compile-Time Metaprogramming
Use Scala 3 inline, transparent inline, and compiletime for compile-time computation and code generation.
Best for: Compile-time computation
Typesafe Config Parsing
Load and parse application configuration with Typesafe Config: HOCON format, defaults, and validation.
Best for: Application configuration management
Exception Handling Patterns
Handle exceptions in Scala: try-catch-finally, Try monad, NonFatal, and custom exceptions.
Best for: Graceful error recovery
Set Operations and Algorithms
Perform set operations: union, intersection, difference, subsets, and practical set algorithms.
Best for: Deduplication and uniqueness
Streaming with fs2
Build composable streaming pipelines with fs2: chunks, transformations, concurrency, and resource safety.
Best for: Streaming data processing
Functional State Management
Manage state purely with State monad: stack-based state, random number generation, and game state.
Best for: Pure state transformations
Database Queries with Slick
Write type-safe database queries with Slick: table definitions, CRUD, joins, and streaming.
Best for: Type-safe database access
Range and Sequence Generators
Generate sequences with Range, tabulate, fill, iterate, and unfold for data generation.
Best for: Test data generation
Multiversal Equality in Scala 3
Use strict equality with CanEqual to prevent comparing unrelated types at compile time.
Best for: Preventing accidental type comparisons
Thread-Safe Concurrent Collections
Use concurrent collections for thread-safe access: TrieMap, concurrent queues, and synchronized wrappers.
Best for: Thread-safe service registries
Phantom Types for Compile-Time Safety
Use phantom types to encode state and constraints at the type level without runtime cost.
Best for: State machine enforcement at compile time
Spark Structured Streaming
Process real-time data with Spark Structured Streaming: sources, transformations, and sinks.
Best for: Real-time event processing
Dependency Injection Patterns
Implement dependency injection in Scala: cake pattern, constructor injection, and ZIO ZLayer.
Best for: Decoupled service architecture
Type Aliases and Abstract Types
Define type aliases, abstract types, and type members for cleaner and more expressive APIs.
Best for: Simplifying complex type signatures
Match Expressions with Guards
Use match expressions with guards, alternatives, and deep patterns for control flow.
Best for: Control flow with pattern matching
SBT Build Configuration
Configure Scala projects with SBT: dependencies, plugins, multi-project builds, and custom tasks.
Best for: Scala project setup
HTTP Server with http4s
Build HTTP servers with http4s: routes, middleware, JSON, and streaming responses.
Best for: REST API development with http4s
Effect Composition Patterns
Compose effects with traverse, sequence, parTraverse, and error accumulation patterns.
Best for: Parallel API calls
Testing with Mocks and Stubs
Write testable Scala code with trait-based mocks, stubs, and dependency substitution.
Best for: Unit testing with dependency injection
XML Processing and Parsing
Parse and generate XML in Scala: literals, pattern matching, XPath-like queries, and transformation.
Best for: XML configuration parsing
Iterator and Lazy Operations
Use Scala iterators for memory-efficient lazy operations: transform, combine, and consume data streams.
Best for: Memory-efficient large data processing
Functor Monad Type Class Hierarchy
Understand the Functor, Applicative, Monad hierarchy: map, ap, flatMap, and their laws.
Best for: Understanding functional abstractions
ZIO Layers and Dependency Management
Use ZIO ZLayer for dependency injection: service definitions, layer composition, and testing.
Best for: Dependency injection with ZIO
Type-Safe Identifiers Pattern
Create type-safe ID wrappers to prevent mixing different entity IDs at compile time.
Best for: Preventing entity ID mixups
Date and Time Operations
Work with dates and times using Java Time API: parsing, formatting, arithmetic, and time zones.
Best for: Date arithmetic and comparison
Automatic Given Instance Derivation
Derive given instances for product and sum types using Scala 3 derives keyword and Mirror.
Best for: Automatic serialization/debugging
Regex Pattern Matching
Use regex with Scala pattern matching: extractors, findAll, replaceAll, and named groups.
Best for: Text parsing and validation
Enum Patterns and Exhaustive Matching
Define and use enums in Scala 3: values, parameters, methods, and exhaustive pattern matching.
Best for: Defining finite sets of values
Mutable Collections and Buffers
Use mutable collections: ArrayBuffer, ListBuffer, mutable Map/Set, and when to choose mutable vs immutable.
Best for: Performance-critical collection building
Variance and Type Bounds
Understand covariance, contravariance, and type bounds: upper bounds, lower bounds, and context bounds.
Best for: Type-safe generic containers
Command-Line Application
Build CLI applications with argument parsing, interactive prompts, and formatted output.
Best for: Command-line tool development
Resource Management with Using
Manage resources safely with Using, try-with-resources, bracket pattern, and Cats Resource.
Best for: Safe file handling
Advanced JSON with Circe
Handle complex JSON with Circe: custom codecs, optics, cursor navigation, and error handling.
Best for: API response parsing
Partial Functions and Composition
Use PartialFunction for handlers, pattern matching functions, and safe composition with orElse/andThen.
Best for: Event handling systems
Akka Streams Data Processing
Build reactive data pipelines with Akka Streams: sources, flows, sinks, and graph DSL.
Best for: Reactive data pipeline processing
Refined and Constrained Types
Create constrained types with validation: non-empty strings, bounded numbers, and validated domain types.
Best for: Domain type validation
Context Parameters with using/given
Use Scala 3 context parameters: given instances, using clauses, context bounds, and implicit scope.
Best for: Type class instances
Java Interop and Collections
Work with Java libraries from Scala: collection conversions, null safety, and API wrapping.
Best for: Using Java libraries from Scala
Custom Extractors with unapply
Create custom pattern matching extractors: unapply, unapplySeq, and boolean extractors.
Best for: Domain-specific pattern matching
Cats Effect Resource Management
Manage resources safely with Cats Effect Resource: acquire-release, composition, and lifecycle.
Best for: Safe resource lifecycle management
Trampolining for Stack Safety
Use trampolining to make recursive algorithms stack-safe without tail recursion.
Best for: Stack-safe mutual recursion
Custom String Interpolation
Create custom string interpolators in Scala: SQL, HTML, JSON, and validated interpolation.
Best for: SQL query building with parameter binding
Future Async Patterns
Work with Scala Futures: composition, error handling, timeout, retry, and parallel execution.
Best for: Asynchronous API calls
Structured Logging Patterns
Implement structured logging in Scala: MDC context, log levels, JSON formatting, and async logging.
Best for: Application observability
Currying and Partial Application
Use currying and partial application for function composition and reusable logic.
Best for: Creating reusable function templates
List Operations Basics
Essential list operations: head, tail, cons, zip, groupBy, sliding, partition, and span.
Best for: Data processing and transformation
Type Conversions and Safe Casting
Convert between types safely: numeric conversions, asInstanceOf alternatives, and pattern-based casting.
Best for: Safe data type conversions
Advanced Map Operations
Advanced Map usage: merge, transform, groupMapReduce, default values, and nested maps.
Best for: Data aggregation and grouping
ZIO Fibers and Concurrency
Use ZIO fibers for lightweight concurrency: fork, join, race, parallel operations, and supervision.
Best for: Lightweight concurrent task execution
Type-Level Programming with Tuples
Work with heterogeneous collections: named tuples, type-safe access, and compile-time operations.
Best for: Generic programming with Mirrors
Tapir Type-Safe API Endpoints
Define and serve HTTP API endpoints with Tapir: type-safe inputs, outputs, error handling, and docs.
Best for: Type-safe HTTP API definitions
Testing with Specs2 Framework
Write readable tests with specs2: acceptance specs, matchers, data tables, and mock integration.
Best for: Behavior-driven development
GroupBy, Partition, and Aggregate
Group, partition, and aggregate collections: groupBy, groupMapReduce, partition, and sliding aggregations.
Best for: Data analysis and reporting