🟣

Kotlin

Kotlin snippets for JVM, Android, and multiplatform development

100 snippets

Showing 100 of 100 snippets

kotlinbeginner

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

#kotlin#null-safety
kotlinbeginner

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

#kotlin#data-class
kotlinbeginner

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

#kotlin#extensions
kotlinbeginner

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

#kotlin#scope-functions
kotlinintermediate

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

#kotlin#coroutines
kotlinintermediate

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

#kotlin#sealed-class
kotlinbeginner

Collections — map, filter, groupBy, and More

Master Kotlin collections: functional transformations, aggregations, grouping, and partition operations.

Best for: Data processing and transformation pipelines

#kotlin#collections
kotlinintermediate

Flow — Reactive Streams with Coroutines

Build reactive pipelines with Kotlin Flow: emit, collect, transform, combine, and error handling.

Best for: Streaming data processing pipelines

#kotlin#flow
kotlinadvanced

Type-Safe DSL Builder

Build domain-specific languages with Kotlin: receiver lambdas, @DslMarker, and nested builders.

Best for: Configuration DSLs for frameworks

#kotlin#dsl
kotlinintermediate

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

#kotlin#delegation
kotlinintermediate

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

#kotlin#spring-boot
kotlinadvanced

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

#kotlin#inline
kotlinadvanced

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

#kotlin#channels
kotlinintermediate

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

#kotlin#sequences
kotlinintermediate

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

#kotlin#result
kotlinintermediate

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

#kotlin#ktor
kotlinbeginner

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

#kotlin#companion-object
kotlinintermediate

Higher-Order Functions and Lambda Patterns

Compose behavior with higher-order functions: function types, lambda receivers, and functional composition.

Best for: Composable transformation pipelines

#kotlin#functional
kotlinadvanced

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

#kotlin#coroutines
kotlinadvanced

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

#kotlin#generics
kotlinbeginner

String Templates and Multiline Strings

Format strings in Kotlin: templates, raw strings, trimMargin, trimIndent, and template processing.

Best for: Dynamic string construction and formatting

#kotlin#strings
kotlinbeginner

Object Declarations — Singletons and Anonymous

Use object declarations for singletons, anonymous objects, and object expressions in Kotlin.

Best for: Thread-safe singleton services

#kotlin#object
kotlinadvanced

Coroutine Exception Handling and Supervision

Handle errors in coroutines: CoroutineExceptionHandler, supervisorScope, try-catch, and error propagation.

Best for: Robust error handling in concurrent operations

#kotlin#coroutines
kotlinbeginner

Enum Classes — Advanced Patterns

Use Kotlin enum classes with properties, methods, interfaces, and companion utilities.

Best for: Type-safe constant sets with behavior

#kotlin#enum
kotlinintermediate

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

#kotlin#testing
kotlinbeginner

Destructuring Declarations

Destructure objects into variables: data classes, maps, pairs, and custom componentN operators.

Best for: Clean variable extraction from complex objects

#kotlin#destructuring
kotlinadvanced

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

#kotlin#stateflow
kotlinintermediate

Operator Overloading

Overload operators in Kotlin: arithmetic, comparison, indexing, invoke, and destructuring.

Best for: Mathematical and scientific computing

#kotlin#operators
kotlinbeginner

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

#kotlin#file-io
kotlinbeginner

Type Aliases for Readable Code

Simplify complex types with typealias: function types, generic types, and callback signatures.

Best for: Simplifying complex function signatures

#kotlin#typealias
kotlinintermediate

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

#kotlin#regex
kotlinintermediate

Kotlinx Serialization — JSON Parsing

Serialize and deserialize JSON with kotlinx.serialization: data classes, custom serializers, and polymorphism.

Best for: API response parsing and generation

#kotlin#serialization
kotlinbeginner

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

#kotlin#validation
kotlinbeginner

Collection Builders — buildList, buildMap, buildSet

Build collections conditionally and dynamically with Kotlin collection builders.

Best for: Conditional list/map construction

#kotlin#collections
kotlinintermediate

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

#kotlin#spring
kotlinadvanced

DSL for HTML Generation

Build a type-safe HTML DSL with Kotlin: lambda receivers, @DslMarker, and nested builders.

Best for: Type-safe template generation

#kotlin#dsl
kotlinbeginner

When Expression — Advanced Matching

Use when as expression and statement: type checks, ranges, destructuring, and guard conditions.

Best for: Exhaustive sealed class handling

#kotlin#when
kotlinadvanced

Custom Property Delegates

Create reusable property delegates: validation, logging, caching, and thread-safe lazy initialization.

Best for: Input validation on property assignment

#kotlin#delegates
kotlinintermediate

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

#kotlin#ktor
kotlinintermediate

Interface Delegation with 'by'

Delegate interface implementations with the 'by' keyword: composition over inheritance patterns.

Best for: Composition over inheritance

#kotlin#delegation
kotlinadvanced

Flow Advanced Operators

Advanced flow operations: debounce, flatMapMerge, conflate, buffer, retry, and custom operators.

Best for: Search input debouncing

#kotlin#flow
kotlinadvanced

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

#kotlin#multiplatform
kotlinadvanced

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

#kotlin#contracts
kotlinintermediate

Coroutine Timeouts and Cancellation

Control coroutine lifecycle: withTimeout, withTimeoutOrNull, isActive checking, and cooperative cancellation.

Best for: API call timeout handling

#kotlin#coroutines
kotlinintermediate

Map Operations — Transform, Merge, Group

Advanced map operations: groupBy, associate, flatMap, merge strategies, and map transformations.

Best for: Data aggregation and grouping

#kotlin#collections
kotlinintermediate

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

#kotlin#null-safety
kotlinintermediate

Dependency Injection with Koin

Set up Koin DI: modules, scoped instances, factory vs single, and parameterized injection.

Best for: Application dependency management

#kotlin#koin
kotlinadvanced

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#functional
kotlinintermediate

Kotlin Gradle DSL — Build Configuration

Configure Gradle builds with Kotlin DSL: dependencies, tasks, plugins, and multi-module setup.

Best for: Kotlin project build configuration

#kotlin#gradle
kotlinbeginner

List Transformation Patterns

Master list operations: windowed, chunked, zip, fold, scan, partition, and custom transforms.

Best for: Data processing pipelines

#kotlin#collections
kotlinadvanced

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

#kotlin#context-receivers
kotlinintermediate

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

#kotlin#value-class
kotlinbeginner

Ranges, Progressions, and Coercion

Use Kotlin ranges: IntRange, custom progressions, coerceIn, and range-based iteration patterns.

Best for: Score and category classification

#kotlin#ranges
kotlinadvanced

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

#kotlin#spring
kotlinintermediate

Map Delegation for Dynamic Properties

Delegate properties to maps: dynamic configuration, JSON-to-object mapping, and flexible data classes.

Best for: Dynamic configuration loading

#kotlin#delegation
kotlinintermediate

Sequence Generators with yield

Create lazy sequences with sequence builders, yield, yieldAll, and custom infinite generators.

Best for: Lazy paginated API consumption

#kotlin#sequences
kotlinintermediate

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

#kotlin#extensions
kotlinadvanced

Annotations and Runtime Reflection

Work with Kotlin annotations and reflection: custom annotations, property inspection, and annotation processing.

Best for: Custom annotation-driven validation

#kotlin#annotations
kotlinadvanced

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

#kotlin#coroutines
kotlinbeginner

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

#kotlin#sam
kotlinintermediate

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

#kotlin#coroutines
kotlinintermediate

Type-Safe Builder for Configuration

Build configuration DSLs: server config, dependency injection setup, and nested builder patterns.

Best for: Application configuration DSLs

#kotlin#builder
kotlinintermediate

Sealed Interfaces — Flexible Hierarchies

Use sealed interfaces for multi-hierarchy modeling: states, results, commands, and event systems.

Best for: Multi-interface state modeling

#kotlin#sealed
kotlinbeginner

String Processing Utilities

Common string operations in Kotlin: split, join, pad, replace, regex, and template processing.

Best for: CSV and delimited data parsing

#kotlin#strings
kotlinintermediate

Multimap, Grouping, and Counting Patterns

Build multimaps, aggregate data, count occurrences, and perform grouped reductions in Kotlin.

Best for: Log aggregation and analysis

#kotlin#collections
kotlinbeginner

Suspend Functions — Basics and Patterns

Understand suspend functions: sequential vs concurrent, suspend composition, and callback wrapping.

Best for: Sequential vs concurrent API calls

#kotlin#coroutines
kotlinadvanced

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

#kotlin#spring
kotlinadvanced

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

#kotlin#generics
kotlinadvanced

SupervisorJob and Error Isolation

Isolate coroutine failures with SupervisorJob: independent child coroutines, partial failure handling.

Best for: Independent failure isolation in microservices

#kotlin#coroutines
kotlinadvanced

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

#kotlin#builder
kotlinadvanced

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

#kotlin#functional
kotlinintermediate

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

#kotlin#ktor
kotlinadvanced

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

#kotlin#coroutines
kotlinintermediate

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

#kotlin#testing
kotlinbeginner

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#value-class
kotlinbeginner

Kotlin Regex Pattern Matching

Use Kotlin regex for validation, extraction, replacing, and destructuring with named groups.

Best for: Input validation for forms and APIs

#kotlin#regex
kotlinadvanced

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

#kotlin#spring-boot
kotlinbeginner

Collection Transformations and Aggregations

Master Kotlin collection operations: groupBy, partition, associate, zip, windowed, and aggregate.

Best for: Data aggregation and reporting

#kotlin#collections
kotlinintermediate

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

#kotlin#state-machine
kotlinintermediate

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

#kotlin#delegation
kotlinadvanced

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

#kotlin#dsl
kotlinadvanced

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

#kotlin#coroutines
kotlinintermediate

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#spring-data
kotlinbeginner

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#null-safety
kotlinadvanced

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#flow
kotlinintermediate

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#result
kotlinbeginner

Kotlin String Manipulation Utilities

Essential string operations in Kotlin: templates, multiline, padding, splitting, regex, and buildString.

Best for: Text formatting and report generation

#kotlin#string
kotlinintermediate

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#inline
kotlinintermediate

Kotlin Operator Overloading

Overload operators for custom types: arithmetic, comparison, indexing, destructuring, and invoke.

Best for: Mathematical libraries with natural syntax

#kotlin#operators
kotlinbeginner

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

#kotlin#delegation
kotlinadvanced

Coroutine Select Expression

Use select expression to await the first result from multiple suspending operations or channels.

Best for: Racing multiple async operations

#kotlin#coroutines
kotlinintermediate

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

#kotlin#testing
kotlinintermediate

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

#kotlin#sealed
kotlinadvanced

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

#kotlin#stateflow
kotlinintermediate

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#compose
kotlinadvanced

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

#kotlin#generics
kotlinbeginner

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

#kotlin#datetime
kotlinintermediate

Functional Composition and Pipelines

Compose functions and build transformation pipelines with Kotlin higher-order functions.

Best for: Data transformation pipelines

#kotlin#functional
kotlinadvanced

Structured Concurrency Patterns

Apply structured concurrency: parallel decomposition, scoped tasks, cancellation, and resource cleanup.

Best for: Parallel API calls with structured lifecycle

#kotlin#coroutines
kotlinintermediate

Kotlin Error Handling Patterns

Comprehensive error handling: sealed result types, validated aggregation, and railway-oriented programming.

Best for: Form validation with error accumulation

#kotlin#error-handling