Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/LukasForst/katlib

Companion to Kotlin standard library
https://github.com/LukasForst/katlib

extensions kotlin kotlin-extensions kotlin-library

Last synced: 3 months ago
JSON representation

Companion to Kotlin standard library

Awesome Lists containing this project

README

        

# Katlib

![CI test](https://github.com/LukasForst/katlib/workflows/CI%20test/badge.svg)
[![Release pipeline](https://github.com/LukasForst/katlib/actions/workflows/release.yml/badge.svg)](https://github.com/LukasForst/katlib/actions/workflows/release.yml)
[![Documentation](https://img.shields.io/badge/docs-online-brightgreeb)](https://katlib.forst.dev/)

Successor of [Ktoolz](https://github.com/blindspot-ai/ktoolz).

Collection of Kotlin extension functions and utilities. This library does not have any dependency.

## Using Katlib

Katlib is available on the Maven Central. Then to import Katlib to Gradle project use:

```Kotlin
implementation("dev.forst", "katlib", "2.2.7")
```

Or with Groovy DSL

```groovy
implementation 'dev.forst:katlib:2.2.7'
```

To import Katlib to Maven project use:

```xml

dev.forst
katlib
2.2.7

```

## Documentation

Available online - [katlib.forst.dev](https://katlib.forst.dev/)

## Contribution

Feel free to submit PR with your favourite extension functions and other cool utilities!

## Examples

The library contains a lot of useful (as well as useless) extensions and functions that were gathered during my (and my colleges) Kotlin
career. Please see [tests](src/test/kotlin/dev/forst/katlib) folder for all possible functions and how to use them. Full documentation can
be found [here](https://katlib.forst.dev/).

Please note that some functions seems like duplicates of the standard library - usually it is not like that as they provide similar
functionality on different interface. For example there's `List.random` but not `Iterable.random` - random on `Iterable` is then implemented
in this library. Some functions are also essentially type aliases (for example `equalsIgnoreCase`) for standard library as I was having hard
time finding correct name.

However, in some cases there might be duplicates, as development of this library started in 2018 and a lot of functions came to standard
library in Kotlin 1.4. - so if you find some duplicates, let me know or create PR that deprecates them in the code.

Following functions are the most popular ones.

#### [Iterable Extensions](src/main/kotlin/dev/forst/katlib/IterableExtensions.kt)

* `Iterable.random` - returns the random element from the iterable
* `Iterable.reduction` - reduce producing list allowing you to set initial value, useful for cumulative sums
* `Iterable>.sumByIndexes` - sums all Lists of integers into single one by indexes
* `Iterable>.sumDoublesByIndexes` - same as previous but with doubles
* `Iterable.mapToSet` - creates set from iterable, transforms with given function
* `Iterable.dominantValueBy` - returns the most frequently occurring value of the given function
* `Iterable.cartesianProduct` - cartesian product between all the elements from two iterables
* `Iterable.forEachNotNull` - performs action on each element that is not null
* `Iterable?>.union` - creates union of all iterables
* `Iterable?>.intersect` - creates intersect of all iterables
* `Iterable.filterNotNullBy` - returns list with only not null results using selector
* `Iterable.singleOrEmpty` - returns single element or null if it wasn't found, throws exception if there are multiple elements
* `Iterable>.splitPairCollection` - returns pair of two lists with left and right values
* `Iterable.setDifferenceBy` - returns difference between two iterables
* `Iterable>.assoc` - returns map from key value pairs but logs case when key is replaced by same key with different value
* `Iterable>.flattenToLists` - returns three lists constructed from triples
* `Iterable.toNavigableSet` - creates NavigableSet
* `Iterable.isEmpty` - determines whether the iterable is empty or not
* `Iterable>.cartesianProduct` - cartesian product between all the elements from nested iterables
* `Iterable>.lazyCartesianProduct` - cartesian product between all the elements from nested iterables as sequence
* `Iterable.zip(b: Iterable, c: Iterable, transform: (a: A, b: B, c: C) -> V)` - zip with three collections instead of two
* `Iterable.sumByFloat(selector: (T) -> Float)` - sums iterable by float selector, because `sumOf` from stdlib does not have
implementation for Floats
* `Iterable.withEach(action: T.() -> Unit)` - performs the given action with each element as a receiver
* `Iterable.withEachIndexed(action: T.(index: Int) -> Unit)` - performs the given action with each element as a receiver, providing sequential index with the element

#### [Map Extensions](src/main/kotlin/dev/forst/katlib/MapExtensions.kt)

* `Map.getWeightedRandom` - randomly selects item with respect to the current weight distribution
* `Map.mergeReduce` - two maps together using the given reduce function
* `Map.join` - joins two maps together using the given join function
* `Map>.swapKeys(): Map>` - swaps keys in two-dimensional maps
* there are multiple `swapKeys` implementations for up to three-dimensional maps, just
browse [the code](src/main/kotlin/dev/forst/katlib/MapExtensions.kt)
* `Map, V>.toTwoLevelMap(): Map>` - creates two-dimensional map from the map of pairs
* `Map, V>.toThreeLevelMap(): Map>>` - creates three-dimensional map from the map of triples
* `Map>.getSecondLevelValues(): Set` - collects all the values from the bottom level into set
* `Map>>.getThirdLevelValues(): Set` - collects all the values from the bottom level into set
* `Iterable>.merge(): Map>` - for each key, merges all the values into one common list

#### [Set Extensions](src/main/kotlin/dev/forst/katlib/SetExtensions.kt)

* `SortedSet.min` - returns minimum of the set or null if empty
* `SortedSet.max` - returns maximum of the set or null

#### [Pair Extensions](src/main/kotlin/dev/forst/katlib/PairExtensions.kt)

* `mapLeft/Right/Pair` - applies given block to left/right/all iterable element/s of the pair

```kotlin
val pair = Pair(listOf(1, 2, 3), 0)
assertEquals(Pair(listOf(11, 12, 13), 0), pair.mapLeft { it + 10 })
```

* `letLeft/Right/Pair` - applies given block to left/right/all element/s of the pair

```kotlin
val pair = Pair(10, 20)
assertEquals(Pair("10", 20), pair.letLeft { it.toString() })
```

#### [Date Extensions](src/main/kotlin/dev/forst/katlib/DateExtensions.kt)

* `getDateRangeTo` - returns list of dates between two `LocalDate`
* `getDaysInInterval` - returns number of days between two `LocalDate` (inclusive)
* `getDayDifference` - returns number of days between two `LocalDate` (exclusive)
* `getWeekOfYear` - returns week of year for given `LocalDate` and optionaly `Locale`

#### [Jackson Extensions](src/main/kotlin/dev/forst/katlib/JacksonExtensions.kt)

To use these, one must include dependency on Jackson

```kotlin
implementation("com.fasterxml.jackson.core", "jackson-databind", jacksonVersion)
implementation("com.fasterxml.jackson.module", "jackson-module-kotlin", jacksonVersion)
```

* `jacksonMapper` - creates jackson mapper with some reasonable settings
* `parseJson` - parses JSON from the string/bytes, returns either instance of null, can log exception if some occurs

```kotlin
val obj: MyDataClass? = parseJson(myJson)
```

* `createJson` - creates JSON from given object
* `createPrettyJson` - creates JSON with pretty print
* `createJsonBytes` - creates JSON in bytes from given object
* `prettyPrintJson` - returns pretty printed JSON value as string

#### [Boolean Extensions](src/main/kotlin/dev/forst/katlib/BooleanExtensions.kt)

`whenTrue` and `whenFalse` - useful extensions mainly used for logging when the oneliners are used.

```kotlin
fun someFunctionIndicatingSuccess(): Boolean =
someComputationReturningBoolean()
.whenFalse {
logger.warning { "someComputationReturningBoolean returned false! Computation probably failed" }
}
```

#### [String Extensions](src/main/kotlin/dev/forst/katlib/StringExtensions.kt)

* `startsWithLetter` - returns true fi string starts with latin letter a-z or A-Z
* `restrictLengthWithEllipsis` - shortens the string to given max length, appends ellipsis

```kotlin
assertEquals("ABCD…", "ABCDEFHG".restrictLengthWithEllipsis(5, "..."))
```

* `toUuid` - converts string to UUID

#### [Instant Extensions](src/main/kotlin/dev/forst/katlib/InstantExtensions.kt)

* `durationToInMilli` - returns absolute difference between two `Instant` values in milliseconds

#### [Crypto Extensions](src/main/kotlin/dev/forst/katlib/CryptoExtensions.kt)

* `hashWithSha256` - produces `SHA-256` of given string/file/bytes
* `computeMd5` - computes MD5 from given byte array, returns base64 encoded data

#### [Miscellaneous Extensions](src/main/kotlin/dev/forst/katlib/OtherExtensions.kt)

* `Optional.orNull(): T?` - from optional to Kotlin optional
* `T.whenNull` - executes block when `this` is null, useful for logging

```kotlin
fun someFunction(): String? =
produceOptionalString()
.whenNull { logger.warn { "produceOptionalString returned null value!" } }
```

* `T.asList` - from `this creates one element list
* `ClosedRange.intersects` - intersection between ranges
* `T.with` - bundles two objects to list
* `validate` - executes invalid block if validating block returns false, useful for validation

```kotlin
validate(
{ someText.startsWith("something") && someText.endsWith("else") },
{ throw IllegalStateException() }
)
```

* `Pair.propagateNull(): Pair?` - if left or right is null, returns null, otherwise pair
* `T.applyIf` - applies given block only if should apply block returns true

```kotlin
byteBuffer.applyIf(shouldReadInt) { getInt() }
```

* `isUuid` - returns true if given string is UUID
* `isUrl` - returns true if give string is URL (with some limitations, see docs)
* `getEnv` - shortcut for `System.getenv`
* `newLine` - shortcut for `System.lineSeparator`
* `ByteArray.toUuid` - Read ByteArray as two longs and combine the to UUID

#### [Services](src/main/kotlin/dev/forst/katlib/Services.kt)

* `TemporalProvider` - Interface providing access to current time via `now` method, very useful when mocking

#### [Array Extensions](src/main/kotlin/dev/forst/katlib/ArrayExtensions.kt)

* `buildArray(builderAction: MutableList.() -> Unit): Array` - builds a new Array by populating a MutableList using the given builderAction and returning an Array with the same elements
* `Array.map(transform: (T) -> R): Array` - Returns an array containing the results of applying the given transform function to each element in the original array
* `Array.mapIndexed(transform: (index: Int, T) -> R): Array` - returns an array containing the results of applying the given transform function to each element and its index in the original array
* `Array.filter(predicate: (T) -> Boolean): Array` - returns an array containing only elements matching the given predicate
* `Array.filterNot(predicate: (T) -> Boolean): Array` - returns an array containing all elements not matching the given predicate
* `Array.filterIndexed(predicate: (index: Int, T) -> Boolean): Array` - returns an array containing only elements matching the given predicate
* `Array<*>.filterIsInstance(): Array` - returns an array containing all elements that are instances of specified type parameter R
* `Array.filterNotNull(): Array` - returns an array containing all elements that are not `null`
* `Array.minus(element: T): Array` - returns an array containing all elements of the original collection without the first occurrence of the given element
* `Array.minus(elements: Array): Array` - returns an array containing all elements of the original collection except the elements contained in the given elements array

#### [Prompt](src/main/kotlin/dev/forst/katlib/Prompt.kt)

* `prompt(promptText: String, exceptionHandler: (e: Exception) -> String? = { null }, transform: (input: String) -> R): R` - prompts user and applies transform to input, invokes exceptionHandler if transform threw an Exception, and repeats prompt