#scala

100 snippets tagged with #scala

scalabeginner

Scala Hello World Application

Create a basic Scala application with main method, string interpolation, and val/var basics.

Best for: Getting started with Scala

#scala#basics
scalabeginner

Pattern Matching Fundamentals

Use Scala pattern matching with guards, type patterns, tuple patterns, and nested extractors.

Best for: Control flow with pattern matching

#scala#pattern-matching
scalabeginner

Case Classes and Objects

Define immutable data with case classes: copy, equality, destructuring, and companion objects.

Best for: Domain modeling with immutable data

#scala#case-class
scalabeginner

Collections Map Filter Fold Operations

Master Scala collections: map, flatMap, filter, fold, groupBy, partition, and zip operations.

Best for: Data transformation and aggregation

#scala#collections
scalaintermediate

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

#scala#option
scalaintermediate

Traits and Mixin Composition

Compose behavior with Scala traits: stackable modifications, self-types, and diamond resolution.

Best for: Composable behavior via mixins

#scala#traits
scalaadvanced

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

#scala#givens
scalaintermediate

For-Comprehensions and Monadic Composition

Use for-comprehensions with Option, Either, Future, and custom monads for elegant composition.

Best for: Chaining optional computations

#scala#for-comprehension
scalabeginner

Higher-Order Functions and Closures

Write and use higher-order functions: function literals, closures, currying, and partial application.

Best for: Building custom control structures

#scala#functions
scalaadvanced

Generics Variance and Type Bounds

Use Scala generics with covariance, contravariance, upper/lower bounds, and context bounds.

Best for: Type-safe container libraries

#scala#generics
scalaintermediate

Futures and Async Programming

Use Scala Futures for async operations: map, flatMap, recover, sequence, and race patterns.

Best for: Asynchronous API calls

#scala#futures
scalabeginner

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

#scala#enum
scalabeginner

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

#scala#extension-methods
scalaintermediate

Parallel Processing with Collections

Process data in parallel using parallel collections, Future.traverse, and batched execution.

Best for: Speeding up CPU-bound operations

#scala#parallel
scalaadvanced

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

#scala#type-class
scalaadvanced

Akka Actor System Basics

Build concurrent applications with Akka actors: message passing, behavior switching, and supervision.

Best for: Concurrent message-passing systems

#scala#akka
scalaadvanced

Cats Effect IO Monad Basics

Use Cats Effect IO for pure functional effects: sequencing, error handling, resource management.

Best for: Pure functional effect management

#scala#cats-effect
scalaadvanced

ZIO Effect System Basics

Build programs with ZIO: effects, error handling, layers, and concurrent operations.

Best for: Typed error handling with ZIO

#scala#zio
scalaintermediate

Apache Spark DataFrame Operations

Process big data with Spark DataFrames: read, filter, aggregate, join, and write operations.

Best for: Big data processing with Spark

#scala#spark
scalabeginner

Sealed Traits and Type Hierarchies

Model domain hierarchies with sealed traits for exhaustive pattern matching and type safety.

Best for: Payment method modeling

#scala#sealed
scalabeginner

Map and HashMap Operations

Work with Scala Maps: create, update, merge, transform, and use default values.

Best for: Configuration management

#scala#map
scalabeginner

String Processing and Regex

Process strings with Scala regex, interpolation, pattern matching extractors, and common operations.

Best for: Text parsing and extraction

#scala#string
scalaintermediate

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

#scala#file-io
scalaintermediate

Lazy Evaluation and LazyList Streams

Use lazy evaluation with LazyList for infinite sequences, memoization, and deferred computation.

Best for: Infinite sequence generation

#scala#lazy
scalaintermediate

HTTP Client with sttp

Make HTTP requests with sttp: GET, POST, headers, JSON bodies, and async backends.

Best for: REST API integration

#scala#http
scalaintermediate

Play Framework REST Controller

Build REST APIs with Play Framework: routes, JSON serialization, async actions, and error handling.

Best for: REST API development

#scala#play
scalaintermediate

Unit Testing with ScalaTest

Write unit tests with ScalaTest: FunSuite, FlatSpec, matchers, mocking, and async testing.

Best for: Unit testing Scala code

#scala#testing
scalaadvanced

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

#scala#opaque-types
scalaintermediate

Given Imports and Exports

Manage given instances with Scala 3 import syntax: selective imports, exports, and priorities.

Best for: Organizing type class instances

#scala#given
scalaadvanced

Concurrent Programming with Atomic Refs

Use atomic references and concurrent data structures for thread-safe state management.

Best for: Lock-free data structures

#scala#concurrent
scalaadvanced

Context Functions and Capability Pattern

Use Scala 3 context functions for dependency injection, capability passing, and builder DSLs.

Best for: Dependency injection without frameworks

#scala#context-functions
scalaintermediate

Recursive Data Structures and Algorithms

Implement recursive data structures: binary trees, linked lists, and tree traversal algorithms.

Best for: Implementing custom data structures

#scala#recursion
scalaintermediate

JSON Parsing with Circe

Parse and generate JSON with Circe: codecs, custom encoders/decoders, and optics.

Best for: REST API JSON handling

#scala#json
scalaadvanced

Spark RDD Transformations and Actions

Process distributed data with Spark RDDs: map, reduce, aggregate, and pair RDD operations.

Best for: Distributed data processing

#scala#spark
scalaadvanced

Advanced Pattern Matching Techniques

Master advanced patterns: custom extractors, unapply, variable binding, and deep matching.

Best for: Custom domain extractors

#scala#pattern-matching
scalaadvanced

Type-Level Programming Basics

Explore Scala 3 type-level programming: match types, singleton types, and type lambdas.

Best for: Type-safe library APIs

#scala#type-level
scalaintermediate

Database Access with Doobie

Query databases with Doobie: SQL interpolation, type-safe queries, transactions, and streaming.

Best for: Type-safe database queries

#scala#database
scalabeginner

Tuples and Product Types

Work with Scala 3 tuples: named tuples, tuple operations, conversions, and generic programming.

Best for: Returning multiple values from functions

#scala#tuples
scalabeginner

Tail Recursion with @tailrec

Write stack-safe recursive functions using @tailrec annotation and accumulator patterns.

Best for: Stack-safe recursive algorithms

#scala#recursion
scalaintermediate

Implicit Conversions in Scala 3

Use Scala 3 Conversion type class for safe implicit conversions and interop patterns.

Best for: Unit conversion libraries

#scala#conversions
scalaadvanced

Cats Monad Transformers

Use Cats monad transformers: EitherT, OptionT, and StateT for composable effect stacks.

Best for: Composable error handling stacks

#scala#cats
scalaintermediate

Collection Views for Lazy Operations

Use collection views for efficient lazy transformations: avoid intermediate collections and improve performance.

Best for: Memory-efficient data processing

#scala#views
scalaintermediate

Property-Based Testing with ScalaCheck

Write property-based tests with ScalaCheck: generators, properties, shrinking, and custom Arbitrary.

Best for: Exhaustive testing with random inputs

#scala#testing
scalaadvanced

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

#scala#dsl
scalaintermediate

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

#scala#validation
scalaintermediate

Union and Intersection Types

Use Scala 3 union and intersection types for flexible and precise type definitions.

Best for: Flexible function parameters

#scala#union-types
scalaadvanced

Type Class Derivation with Mirrors

Derive type class instances automatically using Scala 3 Mirrors and inline metaprogramming.

Best for: Automatic codec generation

#scala#derivation
scalaadvanced

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

#scala#inline
scalabeginner

Typesafe Config Parsing

Load and parse application configuration with Typesafe Config: HOCON format, defaults, and validation.

Best for: Application configuration management

#scala#config
scalabeginner

Exception Handling Patterns

Handle exceptions in Scala: try-catch-finally, Try monad, NonFatal, and custom exceptions.

Best for: Graceful error recovery

#scala#exceptions
scalabeginner

Set Operations and Algorithms

Perform set operations: union, intersection, difference, subsets, and practical set algorithms.

Best for: Deduplication and uniqueness

#scala#set
scalaadvanced

Streaming with fs2

Build composable streaming pipelines with fs2: chunks, transformations, concurrency, and resource safety.

Best for: Streaming data processing

#scala#fs2
scalaintermediate

Functional State Management

Manage state purely with State monad: stack-based state, random number generation, and game state.

Best for: Pure state transformations

#scala#state
scalaintermediate

Database Queries with Slick

Write type-safe database queries with Slick: table definitions, CRUD, joins, and streaming.

Best for: Type-safe database access

#scala#slick
scalabeginner

Range and Sequence Generators

Generate sequences with Range, tabulate, fill, iterate, and unfold for data generation.

Best for: Test data generation

#scala#range
scalaintermediate

Multiversal Equality in Scala 3

Use strict equality with CanEqual to prevent comparing unrelated types at compile time.

Best for: Preventing accidental type comparisons

#scala#equality
scalaintermediate

Thread-Safe Concurrent Collections

Use concurrent collections for thread-safe access: TrieMap, concurrent queues, and synchronized wrappers.

Best for: Thread-safe service registries

#scala#concurrent
scalaadvanced

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

#scala#phantom-types
scalaadvanced

Spark Structured Streaming

Process real-time data with Spark Structured Streaming: sources, transformations, and sinks.

Best for: Real-time event processing

#scala#spark
scalaintermediate

Dependency Injection Patterns

Implement dependency injection in Scala: cake pattern, constructor injection, and ZIO ZLayer.

Best for: Decoupled service architecture

#scala#di
scalabeginner

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

#scala#types
scalabeginner

Match Expressions with Guards

Use match expressions with guards, alternatives, and deep patterns for control flow.

Best for: Control flow with pattern matching

#scala#match
scalabeginner

SBT Build Configuration

Configure Scala projects with SBT: dependencies, plugins, multi-project builds, and custom tasks.

Best for: Scala project setup

#scala#sbt
scalaintermediate

HTTP Server with http4s

Build HTTP servers with http4s: routes, middleware, JSON, and streaming responses.

Best for: REST API development with http4s

#scala#http4s
scalaadvanced

Effect Composition Patterns

Compose effects with traverse, sequence, parTraverse, and error accumulation patterns.

Best for: Parallel API calls

#scala#effects
scalaintermediate

Testing with Mocks and Stubs

Write testable Scala code with trait-based mocks, stubs, and dependency substitution.

Best for: Unit testing with dependency injection

#scala#testing
scalaintermediate

XML Processing and Parsing

Parse and generate XML in Scala: literals, pattern matching, XPath-like queries, and transformation.

Best for: XML configuration parsing

#scala#xml
scalabeginner

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

#scala#iterator
scalaadvanced

Functor Monad Type Class Hierarchy

Understand the Functor, Applicative, Monad hierarchy: map, ap, flatMap, and their laws.

Best for: Understanding functional abstractions

#scala#functor
scalaadvanced

ZIO Layers and Dependency Management

Use ZIO ZLayer for dependency injection: service definitions, layer composition, and testing.

Best for: Dependency injection with ZIO

#scala#zio
scalaintermediate

Type-Safe Identifiers Pattern

Create type-safe ID wrappers to prevent mixing different entity IDs at compile time.

Best for: Preventing entity ID mixups

#scala#type-safety
scalabeginner

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

#scala#date
scalaadvanced

Automatic Given Instance Derivation

Derive given instances for product and sum types using Scala 3 derives keyword and Mirror.

Best for: Automatic serialization/debugging

#scala#derives
scalabeginner

Regex Pattern Matching

Use regex with Scala pattern matching: extractors, findAll, replaceAll, and named groups.

Best for: Text parsing and validation

#scala#regex
scalabeginner

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

#scala#enum
scalabeginner

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

#scala#mutable
scalaadvanced

Variance and Type Bounds

Understand covariance, contravariance, and type bounds: upper bounds, lower bounds, and context bounds.

Best for: Type-safe generic containers

#scala#variance
scalaintermediate

Command-Line Application

Build CLI applications with argument parsing, interactive prompts, and formatted output.

Best for: Command-line tool development

#scala#cli
scalaintermediate

Resource Management with Using

Manage resources safely with Using, try-with-resources, bracket pattern, and Cats Resource.

Best for: Safe file handling

#scala#resource
scalaintermediate

Advanced JSON with Circe

Handle complex JSON with Circe: custom codecs, optics, cursor navigation, and error handling.

Best for: API response parsing

#scala#circe
scalaintermediate

Partial Functions and Composition

Use PartialFunction for handlers, pattern matching functions, and safe composition with orElse/andThen.

Best for: Event handling systems

#scala#partial-function
scalaadvanced

Akka Streams Data Processing

Build reactive data pipelines with Akka Streams: sources, flows, sinks, and graph DSL.

Best for: Reactive data pipeline processing

#scala#akka
scalaintermediate

Refined and Constrained Types

Create constrained types with validation: non-empty strings, bounded numbers, and validated domain types.

Best for: Domain type validation

#scala#refined
scalaintermediate

Context Parameters with using/given

Use Scala 3 context parameters: given instances, using clauses, context bounds, and implicit scope.

Best for: Type class instances

#scala#given
scalabeginner

Java Interop and Collections

Work with Java libraries from Scala: collection conversions, null safety, and API wrapping.

Best for: Using Java libraries from Scala

#scala#java
scalaintermediate

Custom Extractors with unapply

Create custom pattern matching extractors: unapply, unapplySeq, and boolean extractors.

Best for: Domain-specific pattern matching

#scala#extractors
scalaadvanced

Cats Effect Resource Management

Manage resources safely with Cats Effect Resource: acquire-release, composition, and lifecycle.

Best for: Safe resource lifecycle management

#scala#cats-effect
scalaadvanced

Trampolining for Stack Safety

Use trampolining to make recursive algorithms stack-safe without tail recursion.

Best for: Stack-safe mutual recursion

#scala#trampolining
scalaintermediate

Custom String Interpolation

Create custom string interpolators in Scala: SQL, HTML, JSON, and validated interpolation.

Best for: SQL query building with parameter binding

#scala#string-interpolation
scalaintermediate

Future Async Patterns

Work with Scala Futures: composition, error handling, timeout, retry, and parallel execution.

Best for: Asynchronous API calls

#scala#future
scalabeginner

Structured Logging Patterns

Implement structured logging in Scala: MDC context, log levels, JSON formatting, and async logging.

Best for: Application observability

#scala#logging
scalabeginner

Currying and Partial Application

Use currying and partial application for function composition and reusable logic.

Best for: Creating reusable function templates

#scala#currying
scalabeginner

List Operations Basics

Essential list operations: head, tail, cons, zip, groupBy, sliding, partition, and span.

Best for: Data processing and transformation

#scala#list
scalabeginner

Type Conversions and Safe Casting

Convert between types safely: numeric conversions, asInstanceOf alternatives, and pattern-based casting.

Best for: Safe data type conversions

#scala#types
scalabeginner

Advanced Map Operations

Advanced Map usage: merge, transform, groupMapReduce, default values, and nested maps.

Best for: Data aggregation and grouping

#scala#map
scalaadvanced

ZIO Fibers and Concurrency

Use ZIO fibers for lightweight concurrency: fork, join, race, parallel operations, and supervision.

Best for: Lightweight concurrent task execution

#scala#zio
scalaadvanced

Type-Level Programming with Tuples

Work with heterogeneous collections: named tuples, type-safe access, and compile-time operations.

Best for: Generic programming with Mirrors

#scala#type-level
scalaadvanced

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

#scala#tapir
scalaintermediate

Testing with Specs2 Framework

Write readable tests with specs2: acceptance specs, matchers, data tables, and mock integration.

Best for: Behavior-driven development

#scala#testing
scalaintermediate

GroupBy, Partition, and Aggregate

Group, partition, and aggregate collections: groupBy, groupMapReduce, partition, and sliding aggregations.

Best for: Data analysis and reporting

#scala#collections