#kotlin
100 snippets tagged with #kotlin
Null Safety — Elvis, Safe Call, and let
Master Kotlin null safety: safe calls, Elvis operator, let/also scoping, and smart casts.
Best for: Safe navigation through nullable chains
Data Classes — Copy, Destructure, and Equals
Use data classes for immutable models: auto-generated equals, hashCode, copy, and destructuring.
Best for: Immutable domain models and DTOs
Extension Functions and Properties
Add methods to existing classes without inheritance: extension functions, properties, and generic extensions.
Best for: Adding utility methods to third-party types
Scope Functions — let, run, apply, also, with
Master Kotlin scope functions: when to use let, run, apply, also, and with for concise code.
Best for: Object initialization and configuration
Coroutines — launch, async, and Structured Concurrency
Write concurrent code with Kotlin coroutines: launch, async/await, structured concurrency, and dispatchers.
Best for: Parallel API calls in backend services
Sealed Classes and Exhaustive when
Model restricted hierarchies with sealed classes: exhaustive when, data objects, and state machines.
Best for: Type-safe API response handling
Collections — map, filter, groupBy, and More
Master Kotlin collections: functional transformations, aggregations, grouping, and partition operations.
Best for: Data processing and transformation pipelines
Flow — Reactive Streams with Coroutines
Build reactive pipelines with Kotlin Flow: emit, collect, transform, combine, and error handling.
Best for: Streaming data processing pipelines
Type-Safe DSL Builder
Build domain-specific languages with Kotlin: receiver lambdas, @DslMarker, and nested builders.
Best for: Configuration DSLs for frameworks
Delegation — by, lazy, observable, and Custom
Use Kotlin delegation for reusable behavior: by keyword, lazy, observable, vetoable, and map-backed.
Best for: Composing behavior without deep inheritance
Spring Boot REST API in Kotlin
Build a REST API with Spring Boot and Kotlin: controllers, services, error handling, and validation.
Best for: RESTful API development with Kotlin
Inline Functions and Reified Generics
Use inline functions for zero-overhead abstractions: reified type parameters, crossinline, and noinline.
Best for: Type-safe parsing and casting utilities
Channels — Producer-Consumer with Coroutines
Communicate between coroutines with Channels: produce, actor pattern, fan-out/fan-in, and select.
Best for: Producer-consumer patterns in coroutines
Sequences — Lazy Evaluation for Large Data
Process large datasets efficiently with lazy sequences: generateSequence, yield, and custom iterators.
Best for: Processing large datasets without loading all into memory
Result Monad — Functional Error Handling
Handle errors functionally with Kotlin Result: map, recover, fold, and chaining fallible operations.
Best for: Type-safe error handling without exceptions
Ktor HTTP Client — GET, POST, and Auth
Make HTTP requests with Ktor client: GET, POST, headers, auth, retries, and JSON serialization.
Best for: REST API consumption in Kotlin applications
Companion Objects — Static-Like Members and Factories
Use companion objects for factory methods, constants, and implementing interfaces at the class level.
Best for: Factory methods with validated construction
Higher-Order Functions and Lambda Patterns
Compose behavior with higher-order functions: function types, lambda receivers, and functional composition.
Best for: Composable transformation pipelines
Coroutine Mutex and Shared Mutable State
Safely manage shared state across coroutines: Mutex, atomic operations, and actor-based state.
Best for: Thread-safe counters and accumulators
Generics — Variance, Bounds, and Type Projections
Master Kotlin generics: in/out variance, upper bounds, type projections, and generic constraints.
Best for: Type-safe generic APIs and containers
String Templates and Multiline Strings
Format strings in Kotlin: templates, raw strings, trimMargin, trimIndent, and template processing.
Best for: Dynamic string construction and formatting
Object Declarations — Singletons and Anonymous
Use object declarations for singletons, anonymous objects, and object expressions in Kotlin.
Best for: Thread-safe singleton services
Coroutine Exception Handling and Supervision
Handle errors in coroutines: CoroutineExceptionHandler, supervisorScope, try-catch, and error propagation.
Best for: Robust error handling in concurrent operations
Enum Classes — Advanced Patterns
Use Kotlin enum classes with properties, methods, interfaces, and companion utilities.
Best for: Type-safe constant sets with behavior
Testing with JUnit 5 and Kotlin
Write expressive tests in Kotlin: JUnit 5, nested tests, parameterized tests, and extension functions.
Best for: Unit testing Kotlin classes and functions
Destructuring Declarations
Destructure objects into variables: data classes, maps, pairs, and custom componentN operators.
Best for: Clean variable extraction from complex objects
StateFlow and SharedFlow — Hot Streams
Manage state with hot flows: StateFlow for reactive state, SharedFlow for events, and MutableStateFlow.
Best for: Reactive UI state management
Operator Overloading
Overload operators in Kotlin: arithmetic, comparison, indexing, invoke, and destructuring.
Best for: Mathematical and scientific computing
File I/O — Read, Write, and Process
Read and write files in Kotlin: readText, useLines, buffered I/O, and file tree walking.
Best for: Configuration file reading and writing
Type Aliases for Readable Code
Simplify complex types with typealias: function types, generic types, and callback signatures.
Best for: Simplifying complex function signatures
Regex — Match, Replace, and Extract
Use Kotlin regex for pattern matching: find, replace, named groups, and structured extraction.
Best for: Log file parsing and analysis
Kotlinx Serialization — JSON Parsing
Serialize and deserialize JSON with kotlinx.serialization: data classes, custom serializers, and polymorphism.
Best for: API response parsing and generation
Preconditions — require, check, and error
Validate inputs and state with Kotlin preconditions: require, check, error, and custom assertions.
Best for: Input validation at function boundaries
Collection Builders — buildList, buildMap, buildSet
Build collections conditionally and dynamically with Kotlin collection builders.
Best for: Conditional list/map construction
Spring Data JPA with Kotlin
Build data layers with Spring Data JPA in Kotlin: entities, repositories, queries, and pagination.
Best for: CRUD operations with Spring Data
DSL for HTML Generation
Build a type-safe HTML DSL with Kotlin: lambda receivers, @DslMarker, and nested builders.
Best for: Type-safe template generation
When Expression — Advanced Matching
Use when as expression and statement: type checks, ranges, destructuring, and guard conditions.
Best for: Exhaustive sealed class handling
Custom Property Delegates
Create reusable property delegates: validation, logging, caching, and thread-safe lazy initialization.
Best for: Input validation on property assignment
Ktor Server — Routing and Middleware
Build HTTP servers with Ktor: routing DSL, middleware plugins, content negotiation, and error handling.
Best for: REST API server with Ktor
Interface Delegation with 'by'
Delegate interface implementations with the 'by' keyword: composition over inheritance patterns.
Best for: Composition over inheritance
Flow Advanced Operators
Advanced flow operations: debounce, flatMapMerge, conflate, buffer, retry, and custom operators.
Best for: Search input debouncing
Kotlin Multiplatform — Expect/Actual Declarations
Share code across platforms with expect/actual: common interfaces, platform-specific implementations.
Best for: Sharing business logic across JVM and JS
Contracts — Smart Cast Effects
Use Kotlin contracts to help the compiler with smart casting: returns, callsInPlace, and custom implications.
Best for: Custom null-safety assertions
Coroutine Timeouts and Cancellation
Control coroutine lifecycle: withTimeout, withTimeoutOrNull, isActive checking, and cooperative cancellation.
Best for: API call timeout handling
Map Operations — Transform, Merge, Group
Advanced map operations: groupBy, associate, flatMap, merge strategies, and map transformations.
Best for: Data aggregation and grouping
Null Safety — Advanced Patterns
Master null safety in Kotlin: chaining, smart casts, safe builders, orElse patterns, and nullable collections.
Best for: Safe navigation through nested nullable objects
Dependency Injection with Koin
Set up Koin DI: modules, scoped instances, factory vs single, and parameterized injection.
Best for: Application dependency management
Functional Error Handling with Either
Use Either and Option for type-safe error handling: Railway-oriented programming without exceptions.
Best for: Type-safe error handling without exceptions
Kotlin Gradle DSL — Build Configuration
Configure Gradle builds with Kotlin DSL: dependencies, tasks, plugins, and multi-module setup.
Best for: Kotlin project build configuration
List Transformation Patterns
Master list operations: windowed, chunked, zip, fold, scan, partition, and custom transforms.
Best for: Data processing pipelines
Context Receivers — Scoped Functions
Use context receivers for scoped function access: transaction contexts, logging contexts, and DSL building.
Best for: Transaction and logging scope management
Value Classes — Zero-Cost Wrappers
Create type-safe wrappers with value classes: no runtime overhead, domain identifiers, and units.
Best for: Type-safe domain identifiers
Ranges, Progressions, and Coercion
Use Kotlin ranges: IntRange, custom progressions, coerceIn, and range-based iteration patterns.
Best for: Score and category classification
Spring WebFlux with Kotlin Coroutines
Build reactive APIs with Spring WebFlux and Kotlin coroutines: suspend handlers and Flow responses.
Best for: Non-blocking REST APIs with coroutines
Map Delegation for Dynamic Properties
Delegate properties to maps: dynamic configuration, JSON-to-object mapping, and flexible data classes.
Best for: Dynamic configuration loading
Sequence Generators with yield
Create lazy sequences with sequence builders, yield, yieldAll, and custom infinite generators.
Best for: Lazy paginated API consumption
Extension Properties and Receiver Functions
Add properties and functions to existing classes: extension receivers, generic extensions, and DSL patterns.
Best for: Adding utility methods to existing types
Annotations and Runtime Reflection
Work with Kotlin annotations and reflection: custom annotations, property inspection, and annotation processing.
Best for: Custom annotation-driven validation
Structured Concurrency Patterns
Master coroutine structured concurrency: coroutineScope, async/await, fan-out/fan-in, and parallel map.
Best for: Parallel I/O operations with concurrency limits
SAM Conversions and Functional Interfaces
Use SAM conversions with fun interfaces: Java interop, event listeners, and callback patterns.
Best for: Java interop with functional interfaces
Coroutine Dispatchers and Context
Choose the right dispatcher: Default, IO, Main, Unconfined, and custom thread pools for coroutines.
Best for: Choosing optimal dispatcher for workload type
Type-Safe Builder for Configuration
Build configuration DSLs: server config, dependency injection setup, and nested builder patterns.
Best for: Application configuration DSLs
Sealed Interfaces — Flexible Hierarchies
Use sealed interfaces for multi-hierarchy modeling: states, results, commands, and event systems.
Best for: Multi-interface state modeling
String Processing Utilities
Common string operations in Kotlin: split, join, pad, replace, regex, and template processing.
Best for: CSV and delimited data parsing
Multimap, Grouping, and Counting Patterns
Build multimaps, aggregate data, count occurrences, and perform grouped reductions in Kotlin.
Best for: Log aggregation and analysis
Suspend Functions — Basics and Patterns
Understand suspend functions: sequential vs concurrent, suspend composition, and callback wrapping.
Best for: Sequential vs concurrent API calls
Spring Security with JWT Authentication
Configure Spring Security in Kotlin: JWT token generation, validation, role-based access, and security filters.
Best for: JWT-based stateless authentication
Type Class Pattern with Generics
Implement type class patterns in Kotlin: ad-hoc polymorphism, generic serializers, and extension-based dispatch.
Best for: Ad-hoc polymorphism without inheritance
SupervisorJob and Error Isolation
Isolate coroutine failures with SupervisorJob: independent child coroutines, partial failure handling.
Best for: Independent failure isolation in microservices
Builder Inference and Generic DSLs
Use @BuilderInference for type-safe DSL builders with generic type inference and collection construction.
Best for: Type-safe collection construction
Functional Error Handling with Either
Implement Either monad for type-safe error handling with map, flatMap, and fold operations.
Best for: Type-safe error handling without exceptions
Ktor Server Routing and Middleware
Build HTTP APIs with Ktor: routing, content negotiation, authentication, and middleware plugins.
Best for: Building REST APIs with Kotlin-native framework
Coroutine Channels Producer Consumer
Use Kotlin channels for coroutine communication: buffered, conflated, fan-out, and fan-in patterns.
Best for: Coroutine-based producer-consumer patterns
Testing with Kotest and Assertions
Write expressive tests with Kotest: string spec, data-driven tests, property-based testing, and matchers.
Best for: Expressive Kotlin unit testing
Value Classes and Type Aliases
Use value classes for type-safe wrappers without runtime overhead and type aliases for readability.
Best for: Type-safe domain primitives without runtime cost
Kotlin Regex Pattern Matching
Use Kotlin regex for validation, extraction, replacing, and destructuring with named groups.
Best for: Input validation for forms and APIs
Spring WebFlux with Kotlin Coroutines
Build reactive Spring APIs using Kotlin coroutines: suspend functions, Flow, and coRouter DSL.
Best for: Non-blocking REST APIs with Kotlin coroutines
Collection Transformations and Aggregations
Master Kotlin collection operations: groupBy, partition, associate, zip, windowed, and aggregate.
Best for: Data aggregation and reporting
State Machines with Enums and Sealed Classes
Model state machines with Kotlin enums and sealed classes for type-safe state transitions.
Best for: Order lifecycle management
Class Delegation with by Keyword
Use Kotlin's 'by' keyword for class delegation: interface forwarding, decorated behavior, and composition.
Best for: Decorator pattern with minimal boilerplate
Type-Safe DSL Builder Pattern
Create type-safe DSLs in Kotlin with receiver lambdas, @DslMarker, and nested builder scopes.
Best for: HTML/XML document generation
Coroutine Mutex and Synchronization
Synchronize shared mutable state in coroutines with Mutex, atomic operations, and thread confinement.
Best for: Thread-safe shared state in coroutines
Spring Data with Kotlin Repository Patterns
Use Spring Data JPA with Kotlin: entity mapping, custom queries, projections, and specifications.
Best for: Database access with Spring Data JPA in Kotlin
Kotlin Null Safety Complete Guide
Master null safety: safe calls, elvis operator, let/also/run, smart casts, and nullable collection handling.
Best for: Safe handling of nullable data from APIs
Kotlin Flow Operators and Transforms
Master Flow operators: map, filter, combine, zip, debounce, retry, buffer, and custom operators.
Best for: Reactive data streams with transformation
Kotlin Result API Functional Error Handling
Use Kotlin's built-in Result type for functional error handling: runCatching, map, recover, and fold.
Best for: Functional error handling without try-catch
Kotlin String Manipulation Utilities
Essential string operations in Kotlin: templates, multiline, padding, splitting, regex, and buildString.
Best for: Text formatting and report generation
Inline Functions and Reified Generics
Use inline functions with reified type parameters for type-safe operations without reflection.
Best for: Type-safe operations without reflection overhead
Kotlin Operator Overloading
Overload operators for custom types: arithmetic, comparison, indexing, destructuring, and invoke.
Best for: Mathematical libraries with natural syntax
Delegate Properties to a Map
Store class properties in a map using Kotlin delegation for dynamic and flexible data objects.
Best for: Dynamic configuration from external sources
Coroutine Select Expression
Use select expression to await the first result from multiple suspending operations or channels.
Best for: Racing multiple async operations
Testing with MockK Framework
Mock dependencies in Kotlin tests with MockK: relaxed mocks, verify, coEvery, and slot captures.
Best for: Unit testing with mocked dependencies
Sealed Hierarchies for Domain Modeling
Use sealed interfaces and classes for exhaustive domain modeling with when expressions.
Best for: Payment processing with type-safe methods
StateFlow and SharedFlow Usage Patterns
Use hot flows for state management: MutableStateFlow for UI state, SharedFlow for events and broadcasting.
Best for: UI state management in Android/KMP apps
Jetpack Compose UI Basics
Build declarative UIs with Jetpack Compose: composable functions, state, layouts, and modifiers.
Best for: Building Android UIs with declarative syntax
Kotlin Generics Variance In Out Star
Understand Kotlin generics: declaration-site variance with in/out, type projections, and star projection.
Best for: Type-safe container hierarchies
Date and Time Operations in Kotlin
Work with dates and times using java.time: parsing, formatting, duration, period, and timezone handling.
Best for: Date formatting for user interfaces
Functional Composition and Pipelines
Compose functions and build transformation pipelines with Kotlin higher-order functions.
Best for: Data transformation pipelines
Structured Concurrency Patterns
Apply structured concurrency: parallel decomposition, scoped tasks, cancellation, and resource cleanup.
Best for: Parallel API calls with structured lifecycle
Kotlin Error Handling Patterns
Comprehensive error handling: sealed result types, validated aggregation, and railway-oriented programming.
Best for: Form validation with error accumulation