How to import a package in Kotlin
Overview
A package is a group of related classes, enums, functions, sub-packages, and so on.
To import a package in Kotlin, we use the import keyword, followed by the name of the package that needs to be imported.
Syntax
import package-name
Code example
Let’s see how we import a package in Kotlin, in the following code snippet:
// import packageimport kotlin.math.*fun main() {// access method defined in packagevar sqrtOf4 = sqrt(4.0)println(sqrtOf4)}
Code explanation
- Line 2: We import the
mathpackage of Kotlin. - Line 4: We create the
mainfunction. - Line 6: We use the
sqrt()method present in themathpackage to calculate the square root of4.0. - Line 7: We print the result to the console.
Output
We can see the square of 4.0, that is, 2.0 on the console.