Lesson contents

Kotlin — Organizing code across files

Kotlin lets you declare a function at the top level of a file. A package name and an import let another file call that function.

A simple example

Import a function

  1. Start with −2
  2. Do this Import abs from kotlin.math
  3. Result 2
The import lets you call abs directly. Its result is the distance from zero.
Lesson.kt
import kotlin.math.abs

fun main() {
    println(abs(-2))
}
Output
2
Advertisements

Share a function between source files

The helper is a top-level function in package boxes. An import makes it visible by its short name in the entry file. Compile both source files into the same runnable JAR.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Boxes.kt Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Boxes.kt
package boxes

fun remaining(capacity: Int, used: Int): Int = capacity - used
Lesson.kt
import boxes.remaining

fun main() {
    println(remaining(8, 3))
}
Output
5

Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.

Try it yourself

Change the used count from 3 to 8 in the caller.

Check your answer

Running the same command prints 0. No change to the helper is needed.

Kotlin language documentation

Related tags

  • Kotlin
  • modules
  • source files
  • imports