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 package
import kotlin.math.*
fun main() {
// access method defined in package
var sqrtOf4 = sqrt(4.0)
println(sqrtOf4)
}

Code explanation

  • Line 2: We import the math package of Kotlin.
  • Line 4: We create the main function.
  • Line 6: We use the sqrt() method present in the math package to calculate the square root of 4.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.

Free Resources