kotlin library

Kotlin Standard Library

The Kotlin Standard Library provides living essentials for everyday work with Kotlin. These include:

  • Higher-order functions implementing idiomatic patterns (let, apply, use, synchronized, etc).
  • Extension functions providing querying operations for collections (eager) and sequences (lazy).
  • Various utilities for working with strings and char sequences.
  • Extensions for JDK classes making it convenient to work with files, IO, and threading.

See examples at here.

Classes

AfterClass
Marks a function to be executed after a suite.
AfterTest
Marks a function to be invoked before each test.
Annotation
Base interface implicitly implemented by all annotation interfaces.
Asserter
Abstracts the logic for performing assertions.
AsserterContributor
Checks applicability and provides Asserter instance
AsserterResult
Describes the result of an assertion execution.
AssociatedObjectKey
Makes the annotated annotation class an associated object key.
AtomicArray<T>
An Array in which elements are always updated atomically.
AtomicReference<T>
An object reference that is always updated atomically.
BeforeClass
Marks a function to be executed after a suite.
BeforeTest
Marks a function to be invoked before each test.
Cleaner
The marker interface for objects that have a cleanup action associated with them.
Collection<E>
A generic collection of elements.
Debugging
Note: this API is unstable and may change in any release.
DefaultAsserter
Default Asserter implementation to avoid dependency on JUnit or TestNG.
Delegates
Standard property delegates.
DeprecatedSinceKotlin
Marks the annotated declaration as deprecated.
DetachedObjectGraph<T>
Detached object graph encapsulates transferrable detached subgraph which cannot be accessed externally, until it is attached with the attach extension function.
ExperimentalAssociatedObjects
The experimental marker for associated objects API.
ExperimentalEncodingApi
This annotation marks the experimental API for encoding and decoding between binary data and printable ASCII character sequences.
ExperimentalNativeApi
This annotation marks the Kotlin/Native-only standard library API that is considered experimental and is not subject to the general compatibility guarantees given for the standard library: the behavior of such API may be changed or the API may be removed completely in any further release.
ExperimentalObjCName
ExperimentalObjCRefinement
ExperimentalPathApi
This annotation marks the extensions and top-level functions for working with java.nio.file.Path considered experimental.
ExperimentalReflectionOnLambdas
ExperimentalStdlibApi
This annotation marks the standard library API that is considered experimental and is not subject to the general compatibility guarantees given for the standard library: the behavior of such API may be changed or the API may be removed completely in any further release.
ExperimentalTime
This annotation marks the experimental preview of the standard library API for measuring time and working with durations.
ExperimentalTypeInference
FrameworkAdapter
Serves as a bridge to a testing framework.
Future<T>
GC
Note: this API is unstable and may change in any release.
GCInfo
This class represents statistics about the single run of the garbage collector.
Ignore
Marks a test or a suite as ignored.
JUnitAsserter
Implements kotlin.test assertions by delegating them to org.junit.Assert class.
JUnitAsserter5
Implements kotlin.test assertions by delegating them to org.junit.Assert class.
JUnitContributor
Provides JUnitAsserter if org.junit.Assert is found in the classpath.
JUnitContributor5
Provides JUnitAsserter5 if org.junit.Assert is found in the classpath.
JvmName
Specifies the name for the Java class or method which is generated from this element.
JvmOverload
Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values.
JvmRecord
Instructs compiler to mark the class as a record and generate relevant toString/equals/hashCode methods.
JvmStatic
Specifies that an additional static method needs to be generated from this element if it's a function.
KAnnotatedElement
Represents an annotated element and allows to obtain its annotations.
KCallable<R>
Represents a callable entity, such as a function or a property.
KClass<T extends Any>
Represents a class and provides introspection capabilities.
KClassifier
A classifier is either a class or a type parameter.
KDeclarationContainer
KFunction<R>
Represents a function with introspection capabilities.
KotlinTestNamespace
KotlinVersion
Represents a version of the Kotlin standard library.
KParameter
Represents a parameter passed to a function or a property getter/setter, including this and extension receiver parameters.
KProperty<V>
Represents a property, such as a named val or var declaration.
KType
Represents a type.
KTypeParameter
Represents a declaration of a type parameter of a class or a callable.
Lazy<T>
Represents a value with lazy initialization.
MemoryUsage
This class represents statistics of memory usage in one memory pool.
MustBeDocumented
This meta-annotation determines that an annotation is a part of public API and therefore should be included in the generated documentation for the element to which the annotation is applied.
MutableData
Mutable concurrently accessible data buffer.
NativeRuntimeApi
This annotation marks the Kotlin/Native standard library API that tweaks or otherwise accesses the Kotlin runtime behavior.
ObjCName
Instructs the Kotlin compiler to use a custom Objective-C and/or Swift name for this class, property, parameter or function.
ObservableProperty<V>
Implements the core logic of a property delegate for a read/write property that calls callback functions when changed.
ObsoleteWorkersApi
Marks all Worker-related API as obsolete.
Promise<T>
Exposes the JavaScript Promise object to Kotlin.
PropertyDelegateProvider<T, D>
Base interface that can be used for implementing property delegate providers.
Random
ReadOnlyProperty<T, V>
Base interface that can be used for implementing property delegates of read-only properties.
ReadWriteProperty<T, V>
Base interface that can be used for implementing property delegates of read-write properties.
Repeatable
This meta-annotation determines that an annotation is applicable twice or more on a single code element
Result<T>
A discriminated union that encapsulates a successful outcome with a value of type T or a failure with an arbitrary Throwable exception.
Retention
RootSetStatistics
This class represents statistics of the root set for garbage collector run, separated by root set pools.
SharedImmutable
Note: this annotation has effect only in Kotlin/Native with legacy memory manager.
SweepStatistics
This class represents statistics of sweeping in one memory pool.
Target
This meta-annotation indicates the kinds of code elements which are possible targets of an annotation.
Test
Marks a function as a test.
TestNGAsserter
Implements kotlin.test assertions by delegating them to org.testng.Assert class.
TestNGContributor
Provides TestNGAsserter if org.testng.Assert is found in the classpath.
ThreadLocal
Marks a top level property with a backing field or an object as thread local.
Throwable
The base class for all errors and exceptions.
Throws
This annotation indicates what exceptions should be declared by a function when compiled to a JVM method.
Transient
Marks the JVM backing field of the annotated property as transient, meaning that it is not part of the default serialized form of the object.
Volatile
Marks the backing field of the annotated var property as volatile, meaning that reads and writes to this field are atomic and writes are always made visible to other threads.
WeekReference<T extends Any>
Class WeakReference encapsulates weak reference to an object, which could be used to either retrieve a strong reference to an object, or return null, if object was already destroyed by the memory manager.
Worker
WorkerBoundReference<T extends Any>
A shared reference to a Kotlin object that doesn't freeze the referred object when it gets frozen itself.

Enums

AnnotationRetention
Contains the list of possible annotation's retentions.
AnnotationTarget
Contains the list of code elements which are the possible annotation targets.
CopyActionResult
The result of the copyAction function passed to Path.copyToRecursively that specifies further actions when copying an entry.
DeprecationLevel
Possible levels of a deprecation.
DurationUnit
The list of possible time measurement units, in which a duration can be expressed.
FutureState
KParameterKind
Kind represents a particular position of the parameter declaration in the source code, such as an instance, an extension receiver parameter or a value parameter.
KVariance
Represents variance applied to a type parameter on the declaration site (declaration-site variance), or to a type in a projection (use-site variance).
KVisibility
Visibility is an aspect of a Kotlin declaration regulating where that declaration is accessible in the source code. Visibility can be changed with one of the following modifiers: public, protected, internal, private.
LazyThreadSafetyMode
Specifies how a Lazy instance synchronizes initialization among multiple threads.
OnErrorResult
The result of the onError function passed to Path.copyToRecursively that specifies further actions when an exception occurs.
PathWalkOption
An enumeration to provide walk options for Path.walk function. The options can be combined to form the walk order and behavior needed.
TransferMode
Note: modern Kotlin/Native memory manager allows to share objects between threads without additional ceremonies, so TransferMode has effect only in legacy memory manager.

Constants

afterClass → const AfterClass
Marks a function to be executed after a suite.
afterTest → const AfterTest
Marks a function to be invoked after each test.
associatedObjectKey → const AssociatedObjectKey
Makes the annotated annotation class an associated object key.
beforeClass → const BeforeClass
Marks a function to be executed before a suite.
beforeTest → const BeforeTest
Marks a function to be invoked before each test.
DEFAULT_BUFFER_SIZE → const Int
Returns the default buffer size when working with buffered streams.
E → const double
Base of the natural logarithms, approximately 2.71828.
experimentalAssociatedObjects → const ExperimentalAssociatedObjects
The experimental marker for associated objects API.
experimentalEncodingApi → const ExperimentalEncodingApi
This annotation marks the experimental API for encoding and decoding between binary data and printable ASCII character sequences.
experimentalNativeApi → const ExperimentalNativeApi
This annotation marks the Kotlin/Native-only standard library API that is considered experimental and is not subject to the general compatibility guarantees given for the standard library: the behavior of such API may be changed or the API may be removed completely in any further release.
experimentalObjCName → const ExperimentalObjCName
This annotation marks the experimental ObjCName annotation.
experimentalObjCRefinement → const ExperimentalObjCRefinement
This annotation marks the experimental Objective-C export refinement annotations.
experimentalPathApi → const ExperimentalPathApi
This annotation marks the experimental API for Path and decoding between binary data and printable ASCII character sequences.
experimentalReflectionOnLambdas → const ExperimentalReflectionOnLambdas
This annotation marks the experimental kotlin-reflect API that allows to approximate a Kotlin lambda or a function expression instance to a KFunction instance.
experimentalStdlibApi → const ExperimentalStdlibApi
This annotation marks the standard library API that is considered experimental and is not subject to the general compatibility guarantees given for the standard library: the behavior of such API may be changed or the API may be removed completely in any further release.
experimentalTime → const ExperimentalTime
This annotation marks the experimental preview of the standard library API for measuring time and working with durations.
experimentalTypeInference → const ExperimentalTypeInference
The experimental marker for type inference augmenting annotations.
ignore → const Ignore
Marks a test or a suite as ignored.
jvmOverload → const JvmOverload
Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values.
jvmRecord → const JvmRecord
Instructs compiler to mark the class as a record and generate relevant toString/equals/hashCode methods.
jvmStatic → const JvmStatic
Specifies that an additional static method needs to be generated from this element if it's a function.
mustBeDocumented → const MustBeDocumented
This meta-annotation determines that an annotation is a part of public API and therefore should be included in the generated documentation for the element to which the annotation is applied.
nativeRuntimeApi → const NativeRuntimeApi
This annotation marks the Kotlin/Native standard library API that tweaks or otherwise accesses the Kotlin runtime behavior.
obsoleteWorkersApi → const ObsoleteWorkersApi
Marks all Worker-related API as obsolete.
PI → const double
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
repeatable → const Repeatable
This meta-annotation determines that an annotation is applicable twice or more on a single code element
sharedImmutable → const SharedImmutable
Note: this annotation has effect only in Kotlin/Native with legacy memory manager.
test → const Test
Marks a function as a test.
threadLocal → const ThreadLocal
Marks a top level property with a backing field or an object as thread local.
transient → const Transient
Marks the JVM backing field of the annotated property as transient, meaning that it is not part of the default serialized form of the object.
volatile → const Volatile
Marks the backing field of the annotated var property as volatile, meaning that reads and writes to this field are atomic and writes are always made visible to other threads.

Properties

asserter Asserter
Current adapter providing assertion implementations.
no setter
kotlinTestNamespace KotlinTestNamespace
no setter
STAR KTypeProjection
Star projection, denoted by the * character.
no setter

Functions

abs(num x) num
Returns the absolute value of the given value x.
acos(num x) num
Computes the arc cosine of the value x.
arrayListOf<T>(ArrayList<T> list) ArrayList<T>
arrayOf<T>(Array<T> array) Array<T>
Returns an array containing the specified elements.
arrayOfNulls(Int size) Array<void>
Returns an array of objects of the given type with the given size, initialized with null values.
asin(num x) num
Computes the arc sine of the value x.
assertContains<T>(Iterable<T> iterable, T element, {String? message}) → void
Asserts that the iterable contains the specified element, with an optional message.
assertContentEquals<T>({Iterable<T>? expected, Iterable<T>? actual, String? message}) → void
Asserts that the expected iterable is structurally equal to the actual iterable, i.e. contains the same number of the same elements in the same order, with an optional message.
assertEquals<T>(T expected, T actual, {String? message, Double absoluteTolerance = 0}) → void
Asserts that the difference between the actual and the expected is within an absoluteTolerance, with an optional message.
assertFails(void block(), [String? message]) Throwable
Asserts that given function block fails by throwing an exception.
assertFailsWith<T>(void block(), {String? message}) → T
Asserts that a block fails with a specific exception of type T being thrown.
assertFalse({String? message, Boolean? actual, Boolean block()?}) → void
Asserts that the given block returns false with an optional message.
assertFalseNoInline({String? message, required Boolean block()}) → void
assertIs<T>(Any? value, [String? message]) → T
Asserts that value is of type T, with an optional message.
assertIsNot<T>(Any? value, [String? message]) → void
Asserts that value is not of type T, with an optional message.
assertNotEquals<T>(T illegal, T actual, {String? message, Double absoluteTolerance = 0}) → void
Asserts that the difference between the actual and the illegal is not within an absoluteTolerance, with an optional message.
assertNotNull<T extends Any, R>(T? actual, {String? message}) → T
Asserts that the actual value is not null, with an optional message.
assertNotNullNoInline<T extends Any, R>(T? actual, {String? message, R block(T)?}) → void
Asserts that the actual value is not null, with an optional message and a function block to process the not-null value.
assertNotSame<T>(T illegal, T actual, {String? message}) → void
Asserts that actual is not the same instance as illegal, with an optional message.
atan(num x) num
Computes the arc tangent of the value x.
atan2(num y, num x) num
Returns the angle theta of the polar coordinates (r, theta) that correspond to the rectangular coordinates (x, y) by computing the arc tangent of the value y/x.
atomicArray<T>(Int size, T init(Int)) AtomicArray<T>
Creates a new AtomicArray of the given size, where each element is initialized by calling the given init function.
atomicLazy<T>(T initializer()) Lazy<T>
Atomic lazy initializer, could be used in frozen objects, freezes initializing lambda, so use very carefully.
booleanArrayOf(BooleanArray array) BooleanArray
Returns an array containing the specified Boolean values.
byteArrayOf(ByteArray array) ByteArray
Returns an array containing the specified Byte numbers.
cast<T>(Any value) → T
Casts the given value to the class represented by this T object.
cbrt(num x) num
Returns the cube root of x.
ceil(num x) int
Rounds the given value x to an integer towards positive infinity.
charArrayOf(CharArray array) CharArray
Returns an array containing the specified characters.
check(Boolean value, {Any lazyMessage()?}) → void
Throws an IllegalStateException with the result of calling lazyMessage if the value is false.
checkNotNull<T>(T? value, {Any lazyMessage()?}) → T
Throws an IllegalStateException with the result of calling lazyMessage if the value is null.
compareValues<T extends Comparable<T>>(T? a, T? b) Int
Compares two nullable Comparable values. Null is considered less than any value.
contravariant(KType type) KTypeProjection
Creates a contravariant projection of a given type, denoted by the in modifier applied to a type.
cos(num n) num
Computes the cosine of the angle x given in radians.
covariant(KType type) KTypeProjection
Creates a covariant projection of a given type, denoted by the out modifier applied to a type.
createCleaner<T>(T resource, void cleanupAction(T resource)) Cleaner
Creates a Cleaner object that runs cleanupAction with given resource some time after its deallocation.
createTempDir({String prefix = 'tmp', String? suffix, File? directory}) Directory
Creates an empty directory in the specified directory, using the given prefix and suffix to generate its name.
createTempFile({String prefix = 'tmp', String? suffix, File? directory}) File
Creates a new empty file in the specified directory, using the given prefix and suffix to generate its name.
currentStackTrace() Array<StackTrace>
Returns an array of stack trace elements, each representing one stack frame.
doubleArrayOf(DoubleArray array) DoubleArray
Returns an array containing the specified Double numbers.
emptyArray<T>() Array<T>
Returns an empty array of the specified type T.
enumValueOf<T extends Enum>(String name) → T
Returns an enum entry with specified name.
enumValues<T extends Enum>() Array<T>
Returns an array containing enum T entries.
error(Any message) → Never
Throws an IllegalStateException with the given message.
exitProcess({required Int status}) → Never
Terminates the currently running process.
expect<T>(T expected, void block(), {String? message}) → void
Asserts that given function block returns the given expected value and use the given message if it fails.
findAssociatedObject<T extends AnnotationTarget>() Any
If T is an @AssociatedObjectKey-annotated annotation class and this class is annotated with @T (S::class), returns object S.
floatArrayOf(FloatArray array) FloatArray
Returns an array containing the specified Float numbers.
floor(num x) num
Rounds the given value x to an integer towards negative infinity.
getTimeMicros() Long
Gets current system time in microseconds since certain moment in the past, only delta between two subsequent calls makes sense.
getTimeMillis() Long
Gets current system time in milliseconds since certain moment in the past, only delta between two subsequent calls makes sense.
getTimeNanos() Long
Gets current system time in seconds since certain moment in the past, only delta between two subsequent calls makes sense.
hypot(num x, num y) num
Computes sqrt(x^2 + y^2) without intermediate overflow or underflow.
intArrayOf(IntArray array) IntArray
Returns an array containing the specified Int numbers.
invariant(KType type) KTypeProjection
Creates an invariant projection of a given type.
lazy<T>({required LazyThreadSafetyMode mode, required T initializer()}) Lazy<T>
Creates a new instance of the Lazy that uses the specified initialization function initializer and the default thread-safety mode LazyThreadSafetyMode.SYNCHRONIZED.
lazyOf<T>(T value) Lazy<T>
Creates a new instance of the Lazy that is already initialized with the specified value.
listOf<T>(List<T> list) List<T>
ln(num x) num
Computes the natural logarithm (base E) of the value x.
ln1p(num x) num
Computes ln(x + 1).
log(num x) num
Computes the logarithm of the value x to the given base.
log10(num x) num
Computes the common logarithm (base 10) of the value x.
log2(num x) num
Computes the common logarithm (base 2) of the value x.
longArrayOf(LongArray array) LongArray
Returns an array containing the specified Long numbers.
mapOf<K, V>(Map<K, V> map) Map<K, V>
max(num a, num b) num
Returns the greater of two values.
maxOf<T extends Comparable<T>>(T a, {required Array<T> others, Comparator<T>? comparator}) → T
Returns the greater of the given values according to the order specified by the given comparator.
measureNanoTime(void block()) Long
Executes the given block and returns elapsed time in milliseconds.
measureTime(void block()) Duration
Executes the given function block and returns the duration of elapsed time interval.
measureTimedValue<T>(T block()) TimedValue<T>
Executes the given function block and returns an instance of TimedValue class, containing both the result of the function execution and the duration of elapsed time interval.
measureTimeMicros(void block()) Long
Executes the given block and returns elapsed time in microseconds.
measureTimeMillis(void block()) Long
Executes the given block and returns elapsed time in milliseconds.
min(num a, num b) num
Returns the smaller of two values.
minOf<T extends Comparable<T>>(T a, {required Array<T> others, Comparator<T>? comparator}) → T
Returns the smaller of the given values according to the order specified by the given comparator.
naturalOrder<T>() Comparator<T>
Returns a comparator that compares Comparable objects in natural order.
println(Any message) → void
Prints the given message and the line separator to the standard output stream.
readline() String?
Reads a line of input from the standard input stream.
readln() String
Reads a line of input from the standard input stream and returns it, or throws a RuntimeException if EOF has already been reached when readln is called.
readlnOrNull() String?
Reads a line of input from the standard input stream and returns it, or return null if EOF has already been reached when readlnOrNull is called.
repeat(Int times, void action(Int)) → void
Executes the given function action specified number of times.
require({required Boolean value, Any lazyMessage()?}) → void
Throws an IllegalArgumentException if the value is false.
requireNotNull<T>(T? value, {Any lazyMessage()?}) → T
Throws an IllegalStateException with the result of calling lazyMessage if the value is null.
round(num x) int
Rounds the given value x towards the closest integer with ties rounded towards even integer.
safeCast<T>(Any value) → T?
Casts the given value to the class represented by this T object.
shortArrayOf(ShortArray array) ShortArray
Returns an array containing the specified Short numbers.
sin(num x) num
Computes the sine of the angle x given in radians.
sqrt(num x) num
Computes the positive square root of the value x.
tan(num x) num
Computes the tangent of the angle x given in radians.
TODO([String? reason]) → void
Always throws NotImplementedError stating that operation is not implemented.
todo(void block()) → void
Takes the given block of test code and doesn't execute it.
truncate(num x) num
Rounds the given value x to an integer towards zero.
typeOf<T>(T value) Type
Returns a runtime representation of the given reified type T as an instance of Type.
waitForMultipleFutures<T>(Int millis) Set<Future<T>>
waitWorkerTermination(Worker worker) → void
withWorker<R>({String? name, Boolean errorReporting = true, required R block()}) → R
Executes block with new Worker as resource, by starting the new worker, calling provided block (in current context) with newly started worker as this and terminating worker after the block completes.

Typedefs

AccessDeniedException = PathAccessException
An exception class which is used when we have not enough access for some operation.
Any = Object
The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.
Array<T> = List<T>
Represents an array (specifically, a Java array when targeting the JVM platform).
ArrayList<T> = Array<T>
Boolean = bool
Represents a value which is either true or false.
BooleanArray<T> = Array<Boolean>
An array of booleans.
Byte = int
Represents a 8-bit signed integer.
ByteArray<T> = Array<Byte>
An array of bytes.
Char = String
Represents a 16-bit Unicode character.
CharArray<T> = Array<Char>
An array of chars.
Comparator<T> = Comparable<T>
Double = double
Represents a double-precision 64-bit IEEE 754 floating point number.
DoubleArray<T> = Array<Double>
An array of doubles.
FileAlreadyExistsException = PathExistsException
An exception class which is used when some file to create or copy to already exists.
Float = double
Represents a single-precision 32-bit IEEE 754 floating point number.
FloatArray<T> = Array<Float>
An array of floats.
fun = void
IndexedValue<T> = (Int, T)
Data class representing a value from a collection or sequence, along with its index in that collection or sequence.
Int = int
Represents a 32-bit signed integer.
IntArray<T> = Array<Int>
An array of ints.
IntRange = (Int, Int)
A range of values of type Int.
JvmRepeatable = Repeatable
Makes the annotation class repeatable in Java and Kotlin.
KTypeProjection = (KType?, KVariance?)
Represents a type projection.
Long = int
Represents a 64-bit signed integer.
LongArray<T> = Array<Long>
An array of longs.
NoSuchFileException = PathNotFoundException
An exception class which is used when file to copy does not exist.
Nothing = Never
Nothing has no instances.
NotImplementedError = UnimplementedError
Number = num
Superclass for all platform classes representing numeric values.
Pair<A, B> = (A, B)
Represents a generic pair of two values.
Short = int
Represents a 16-bit signed integer.
ShortArray<T> = Array<Short>
An array of shorts.
TimedValue<T> = (Duration, T)
Data class representing a result of executing an action, along with the duration of elapsed time interval.
TimeUnit = DurationUnit
Triple<A, B, C> = (A, B, C)
Represents a triad of values.
UByte = int
UByteArray = Array<UByte>
UInt = Int
ULong = Long
Unit = void
The type with only one value: the Unit object.
UShort = Short
val<T> = T
Declares a read-only property or local variable.
vararg<T> = List<T>
Allows passing a variable number of arguments for a parameter.

Exceptions / Errors

FreezingException
Exception thrown whenever freezing is not possible.
IllegalCallableAccessException
An exception that is thrown when call is invoked on a callable or get or set is invoked on a property and that callable is not accessible (in JVM terms) from the calling method.
IllegalPropertyDelegateAccessException
An exception that is thrown when getDelegate is invoked on a KProperty object that was not made accessible with isAccessible.
IllegalStateException
InvalidMutabilityException
Exception thrown whenever we attempt to mutate frozen objects.
KotlinReflectionNotSupportedError
NoSuchPropertyException
An exception that is thrown when the code tries to introspect a property of a class or a package and that class or the package no longer has that property.
RuntimeException