Intermediate: Libraries and APIs
To get the most out of Kotlin, use existing libraries and APIs so you can spend more time coding and less time reinventing the wheel.
Libraries distribute reusable code that simplifies common tasks. Within libraries, there are packages and objects that group related classes, functions, and utilities. Libraries expose APIs (Application Programming Interfaces) as a set of functions, classes, or properties that developers can use in their code.
Let's explore what's possible with Kotlin.
The standard library
Kotlin has a standard library that provides essential types, functions, collections, and utilities to make your code concise and expressive. A large portion of the standard library (everything in the kotlin
package) is readily available in any Kotlin file without the need to import it explicitly:
However, some parts of the standard library require an import before you can use them in your code. For example, if you want to use the standard library's time measurement features, you need to import the kotlin.time
package.
At the top of your file, add the import
keyword followed by the package that you need:
The asterisk *
is a wildcard import that tells Kotlin to import everything within the package. You can't use the asterisk *
with companion objects. Instead, you need to explicitly declare the members of a companion object that you want to use.
For example:
This example:
Imports the
Duration
class and thehours
andminutes
extension properties from its companion object.Uses the
minutes
property to convert30
into aDuration
of 30 minutes.Uses the
hours
property to convert0.5
into aDuration
of 30 minutes.Checks if both durations are equal and prints the result.
Search before you build
Before you decide to write your own code, check the standard library to see if what you're looking for already exists. Here's a list of areas where the standard library already provides a number of classes, functions, and properties for you:
To learn more about what else is in the standard library, explore its API reference.
Kotlin libraries
The standard library covers many common use cases, but there are some that it doesn't address. Fortunately, the Kotlin team and the rest of the community have developed a wide range of libraries to complement the standard library. For example, kotlinx-datetime
helps you manage time across different platforms.
You can find useful libraries on our search platform. To use them, you need to take extra steps, like adding a dependency or plugin. Each library has a GitHub repository with instructions on how to include it in your Kotlin projects.
Once you add the library, you can import any package within it. Here's an example of how to import the kotlinx-datetime
package to find the current time in New York:
This example:
Imports the
kotlinx.datetime
package.Uses the
Clock.System.now()
function to create an instance of theInstant
class that contains the current time and assigns the result to thenow
variable.Prints the current time.
Uses the
TimeZone.of()
function to find the time zone for New York and assigns the result to thezone
variable.Calls the
.toLocalDateTime()
function on the instance containing the current time, with the New York time zone as an argument.Assigns the result to the
localDateTime
variable.Prints the time adjusted for the time zone in New York.
Opt in to APIs
Library authors may mark certain APIs as requiring opt-in before you can use them in your code. They usually do this when an API is still in development and may change in the future. If you don't opt in, you see warnings or errors like this:
To opt in, write @OptIn
followed by parentheses containing the class name that categorizes the API, appended by two colons ::
and class
.
For example, the uintArrayOf()
function from the standard library falls under @ExperimentalUnsignedTypes
, as shown in the API reference:
In your code, the opt-in looks like:
Here's an example that opts in to use the uintArrayOf()
function to create an array of unsigned integers and modifies one of its elements:
This is the easiest way to opt in, but there are other ways. To learn more, see Opt-in requirements.
Practice
Exercise 1
You are developing a financial application that helps users calculate the future value of their investments. The formula to calculate compound interest is:
Where:
A
is the amount of money accumulated after interest (principal + interest).P
is the principal amount (the initial investment).r
is the annual interest rate (decimal).n
is the number of times interest is compounded per year.t
is the time the money is invested for (in years).
Update the code to:
Import the necessary functions from the
kotlin.math
package.Add a body to the
calculateCompoundInterest()
function that calculates the final amount after applying compound interest.
Exercise 2
You want to measure the time it takes to perform multiple data processing tasks in your program. Update the code to add the correct import statements and functions from the kotlin.time
package:
Exercise 3
There's a new feature in the standard library available in the latest Kotlin release. You want to try it out, but it requires opt-in. The feature falls under @ExperimentalStdlibApi
. What should the opt-in look like in your code?
What's next?
Congratulations! You've completed the intermediate tour! As a next step, check out our tutorials for popular Kotlin applications:
Create a cross-platform application for Android and iOS from scratch and: