Katlib
Successor of 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:
implementation("pw.forst", "katlib", "some-latest-version")
Or with Groovy DSL
implementation 'pw.forst:katlib:some-latest-version'
To import Katlib to Maven project use:
<dependency>
<groupId>pw.forstgroupId>
<artifactId>katlibartifactId>
<version>some-latest-versionversion>
dependency>
Documentation
Available online - katlib.forst.pw
Contribution
Feel free to submig PR with your faviourite 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 folder for all possible functions and how to use them. Full documentation can be found here.
Following functions are the most popular ones.
Iterable Extensions
Iterable
- returns the random element from the iterable.getRandomElement Iterable
- reduce producing list, useful for cumulative sums.reduction Iterable
- sums iterable by long value with selector (deprecated since Kotlin 1.4.0).sumByLong Iterable
- sums all Lists of integers into single one by indexes>.sumByIndexes Iterable
- same as previous but with doubles>.sumDoublesByIndexes Iterable
- returns the largest value of given iterable by provided selector.maxValueBy Iterable
- same as previous, but smallest value.minValueBy Iterable
- creates set from iterable, transforms with given function.mapToSet Iterable
- returns the most frequently occurring value of the given function.dominantValueBy Iterable
- cartesian product between all the elements from two iterables.cartesianProduct Iterable
- performs action on each element that is not null.forEachNotNull Iterable
- creates union of all iterables?>.union Iterable
- creates intersect of all iterables?>.intersect Iterable
- returns list with only not null results using selector.filterNotNullBy Iterable
- returns single element or null if it wasn't found, throws exception if there are multiple elements.singleOrEmpty Iterable
- returns pair of two lists with left and right values>.splitPairCollection Iterable
- returns difference between two iterables.setDifferenceBy Iterable
- returns map from key value pairs but logs case when key is replaced by same key with different value>.assoc Iterable
- returns three lists constructed from triples>.flattenToLists Iterable
- creates NavigableSet.toNavigableSet Iterable
- determines whether the iterable is empty or not.isEmpty Iterable
- cartesian product between all the elements from nested iterables>.cartesianProduct Iterable
- cartesian product between all the elements from nested iterables as sequence>.lazyCartesianProduct Iterable.zip(b: Iterable, c: Iterable
- zip with three collections instead of two, transform: (a: A, b: B, c: C) -> V) Iterable
- sums iterable by float selector, because.sumByFloat(selector: (T) -> Float) sumOf
from stdlib does not have implementation for Floats
Map Extensions
Map
- randomly selects item with respect to the current weight distribution.getWeightedRandom Map
- two maps together using the given reduce function.mergeReduce Map
- joins two maps together using the given join function.join Map
- swaps keys in two-dimensional maps>.swapKeys(): Map > - there are multiple
swapKeys
implementations for up to three-dimensional maps, just browse the code Map
- creates two-dimensional map from the map of pairs, V>.toTwoLevelMap(): Map > Map
- creates three-dimensional map from the map of triples, V>.toThreeLevelMap(): Map >> Map
- collects all the values from the bottom level into set>.getSecondLevelValues(): Set Map
- collects all the values from the bottom level into set>>.getThirdLevelValues(): Set Iterable
- for each key, merges all the values into one common list
Set Extensions
SortedSet.min
- returns minimum of the set or null if emptySortedSet.max
- returns maximum of the set or null
Pair Extensions
mapLeft/Right/Pair
- applies given block to left/right/all iterable element/s of the pair
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
val pair = Pair(10, 20)
assertEquals(Pair("10", 20), pair.letLeft { it.toString() })
Date Extensions
getDateRangeTo
- returns list of dates between twoLocalDate
getDaysInInterval
- returns number of days between twoLocalDate
(inclusive)getDayDifference
- returns number of days between twoLocalDate
(exclusive)getWeekOfYear
- returns week of year for givenLocalDate
and optionalyLocale
Jackson Extensions
To use these, one must include dependency on Jackson
implementation("com.fasterxml.jackson.core", "jackson-databind", jacksonVersion)
implementation("com.fasterxml.jackson.module", "jackson-module-kotlin", jacksonVersion)
jacksonMapper
- creates jackson mapper with some reasonable settingsparseJson
- parses JSON from the string/bytes, returns either instance of null, can log exception if some occurs
val obj: MyDataClass? = parseJson<MyDataClass>(myJson)
createJson
- creates JSON from given objectcreatePrettyJson
- creates JSON with pretty printcreateJsonBytes
- creates JSON in bytes from given objectprettyPrintJson
- returns pretty printed JSON value as string
Boolean Extensions
whenTrue
and whenFalse
- useful extensions mainly used for logging when the oneliners are used.
fun someFunctionIndicatingSuccess(): Boolean =
someComputationReturningBoolean()
.whenFalse {
logger.warning { "someComputationReturningBoolean returned false! Computation probably failed" }
}
String Extensions
startsWithLetter
- returns true fi string starts with latin letter a-z or A-ZrestrictLengthWithEllipsis
- shortens the string to given max length, appends ellipsis
assertEquals("ABCD…", "ABCDEFHG".restrictLengthWithEllipsis(5, "..."))
toUuid
- converts string to UUID
Instant Extensions
durationToInMilli
- returns absolute difference between twoInstant
values in milliseconds
Crypto Extensions
hashWith256
- producesSHA-256
of given string/file/bytes.
Miscellaneous Extensions
Optional
- from optional to Kotlin optional.orNull(): T? T.whenNull
- executes block whenthis
is null, useful for logging
fun someFunction(): String? =
produceOptionalString()
.whenNull { logger.warn { "produceOptionalString returned null value!" } }
T.asList
- from `this creates one element listClosedRange
- intersection between ranges.intersects T.with
- bundles two objects to listvalidate
- executes invalid block if validating block returns false, useful for validation
validate(
{ someText.startsWith("something") && someText.endsWith("else") },
{ throw IllegalStateException() }
)
Pair .propagateNull(): Pair ?
- if left or right is null, returns null, otherwise pairT.applyIf
- applies given block only if should apply block returns true
byteBuffer.applyIf(shouldReadInt) { getInt() }
isUUID
- returns true if given string is UUIDiSURL
- returns true if give string is URL (with some limitations, see docs)getEnv
- shortcut forSystem.getenv
newLine
- shortcut forSystem.lineSeparator
ByteArray.toUuid
- Read ByteArray as two longs and combine the to UUID
Services
TimeProvider
- Interface providing access to current time vianow
method, very useful when mocking