Precondition error checking for Kotlin

Overview

Kotlin Preconditions Build Status

kotlin-preconditions will assist you in ensuring all of your invariants are met before an operation is executed.

Usage

kotlin-preconditions provides a powerful DSL for defining preconditions:

checkThat(1) { isLt(2) }
checkThat(listOf(1, 2)) { contains(1) }

requireThat(1) { isLt(2) }
requireThat(listOf(1, 2)) { contains(1) }

If any of the preconditions are not met then checkThat will throw an IllegalStateException and requireThat will throw an IllegalArgumentException. The exception message will be generated lazily, so your application does not waste resources on evaluating objects that may not trigger an exception.

Compose your preconditions the way you like it:

val list = listOf(1, 2)

requireThat(list) { contains(3) or contains(1) and not(hasSize(3)) }

// nested preconditions
val text: String? = "hello"

requireThat(text) {
    not(isNull()) and {
        hasLength(6) or { startsWith("he") and endsWith("llo") }
    }
}

API Overview

Aliases

Instead of checkThat and requireThat you can also use check and require.

val value = "hello"

check(value) { startsWith("he") and hasLength(5) and not(includes("io")) }
require(value) { startsWith("he") and hasLength(5) and not(includes("io")) }

String preconditions

val value = "hello"

requireThat(value) { startsWith("he") and hasLength(5) and not(includes("io")) }
requireThat(value) { includes("ll") }
requireThat(value) { matches("hello") }
requireThat(value) { endsWith("lo") }
requireThat(value) { hasLength(5) }
requireThat(value) { not(isBlank()) }
requireThat(value) { not(isEmpty()) }
requireThat(value) { hasLengthBetween(1, 5) }

Collection preconditions

val list = listOf(1, 2)

requireThat(list) { hasSize(2) }
requireThat(list) { contains(1) or contains(3) and not(hasSize(3)) }
requireThat(list) { containsAll(1, 2) }
requireThat(list) { containsAll(list) }
requireThat(list) { isSorted() }

Comparable preconditions

requireThat(1) { isLt(2) }
requireThat(1) { isLte(1) }
requireThat(1) { isGt(0) }
requireThat(1) { isGte(1) }
requireThat(1) { isBetween(0..2) }

Map preconditions

val map = mapOf(1 to "1")

requireThat(map) { hasKey(1) }
requireThat(map) { hasValue("1") }
requireThat(map) { contains(1, "1") }

Object preconditions

val result = Result(true)

requireThat(result) { not(isNull()) }
requireThat(result) { isEqualTo(result) }
requireThat(result) { isSameInstanceAs(result) }

Composed preconditions

val value = "hello"

requireThat(value) { startsWith("he") and hasLength(5) and not(includes("io")) }

Labels

val numbers = listOf(1, 2)

requireThat(numbers, "Numbers") { contains(3) or contains(1) and not(hasSize(3)) }

Custom matchers

Custom matchers can be added by using extension functions:

data class Car(val age: Int)

fun PreconditionBlock<Car>.hasAge(expected: Int) = object : Matcher<Car>() {
    override fun test(condition: Condition<Car>) = condition.test {
        withResult(value.age == expected) { "expected car to be $expected years old, but was ${value.age}" }
    }
}

requireThat(Car(22)) { hasAge(22) }

Installation

Maven:

<dependency>
  <groupId>com.github.spoptchev</groupId>
  <artifactId>kotlin-preconditions</artifactId>
  <version>6.1.0</version>
</dependency>

Gradle:

compile 'com.github.spoptchev:kotlin-preconditions:6.1.0'
You might also like...
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

A sample skeleton backend app built using Spring Boot kotlin, Expedia Kotlin Graphql, Reactive Web that can be deployed to Google App Engine Flexible environmennt

spring-kotlin-gql-gae This is a sample skeleton of a backend app that was built using: Spring Boot(Kotlin) Reactive Web Sprinng Data R2DBC with MYSQL

Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Learn-kotlin - Learning more about Kotlin in various content

Kotlin study roadmap https://kotlinlang.org/docs/reference/ Getting Started Basi

Mis experimentos con Kotlin para JetBrains Academy, certificación de Kotlin donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema.
Mis experimentos con Kotlin para JetBrains Academy, certificación de Kotlin donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema.

Kotlin Academy Mis experimentos con Kotlin para JetBrains donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema. Acerca de

Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto Kotlin Collections Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da

Kotlin-GraphQL-Apollo - Sencillo cliente para consumir una API GraphQL con Apollo usando Kotlin
Kotlin-GraphQL-Apollo - Sencillo cliente para consumir una API GraphQL con Apollo usando Kotlin

Kotlin GraphQL Apollo Sencillo cliente para consumir una API GraphQL con Apollo

DS-for-Kotlin - Some classic data sturctures write in kotlin for fun

DS-for-Kotlin Just write some classic data structure by kotlin during my leisure

Account-hexa-service-kotlin - Microservice with Kotlin using Hexagonal architecture

Microservice Construindo microservice de conta para fins Didáticos. Objetivos Cr

Comments
  • Upgrade Kotlin to 1.2.31

    Upgrade Kotlin to 1.2.31

    Attempting to use this library with any Kotlin 1.2 project would issue a warning for JARs in the classpath with different major/minor versions. By updating the library to Kotlin 1.2 those warnings are corrected.

    opened by rpsrosario 2
  • DSL changes

    DSL changes

    Switching from to to should.

    to is colliding with the standard Kotlin standard library function public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

    opened by spoptchev 0
Owner
Spas Poptchev
Freelance Full-Stack Software Engineer
Spas Poptchev
🪟 Pluggable Ktor plugin to implement Sentry for error handling and request contexts

?? Ktor Plugin for Sentry Pluggable Ktor plugin to implement Sentry for error handling and request contexts. What is this library? This basically impl

Noel 3 Dec 6, 2022
Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Kotlin_practice_problems Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Aman 0 Oct 14, 2021
Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

Mockative 121 Dec 26, 2022
Kotlin-oop - Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto React OOP Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura

Marcos Felipe 1 Jan 5, 2022
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
Kotlin TodoMVC – full-stack Kotlin application demo

Kotlin full stack TodoMVC This project is an example implementation of the TodoMVC app written in Kotlin. More specifically, it's the Kotlin port of t

Gyula Voros 22 Oct 3, 2022
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

Jorge Sánchez Fernández 29 Oct 3, 2022
Small kotlin library for persisting _single instances_ of kotlin data classes

PerSista Small library for persisting single instances of kotlin data classes. NB: PerSista uses typeOf() internally which is marked as @ExperimentalS

Eric Donovan 5 Nov 13, 2022
Kotlin Leaning Notes from Udacity Course | Kotlin Bootcamp for Programmers by Google

Kotlin Beginners Notes These are all personal notes taken from the Udacity Course (ud9011) of Kotlin Bootcamp for Programmers by Google as well as oth

Süha Tanrıverdi 34 Dec 10, 2022
Saga pattern implementation in Kotlin build in top of Kotlin's Coroutines.

Module Saga Website can be found here Add in build.gradle.kts repositories { mavenCentral() } dependencies { implementation("io.github.nomisr

Simon Vergauwen 50 Dec 30, 2022