Beginner 5 min readKotlin 2.0

Kotlin Program Structure โ€” How a Kotlin File is Organized

Unlike Java, Kotlin does not require classes to contain all code. Functions and variables can live at the top level of a file.

What You Will Learn

  • What a Kotlin source file contains
  • How packages work
  • What top-level functions and variables are
  • How to split code across multiple files

Parts of a Kotlin File

A typical Kotlin .kt file can contain: 1. **Package declaration** (optional, must be first) 2. **Import statements** 3. **Top-level declarations** โ€” functions, classes, objects, variables

Syntax

kotlin
// Optional: package declaration
package com.kotlinguide.tutorials

// Optional: imports
import kotlin.math.sqrt

// Top-level function (no class needed)
fun greet(name: String) = "Hello, $name"

// Entry point
fun main() {
    println(greet("Kotlin"))
}

Complete File Structure

kotlin
package com.example

import kotlin.math.PI

val siteName = "KotlinGuide"

fun circleArea(radius: Double): Double = PI * radius * radius

fun main() {
    println("Welcome to $siteName")
    println("Area: ${circleArea(5.0)}")
}
Output
Welcome to KotlinGuide Area: 78.53981633974483

The package declaration groups related code. The import brings in PI from kotlin.math. siteName is a top-level val โ€” shared across the file. Both functions exist at the top level without any class wrapper.

Beginner Tip: You do not need to match the file name to any class name in Kotlin. One file can have many functions and classes.
The package declaration is optional. If omitted, the file belongs to the default package.

Top-Level Declarations

In Kotlin, you can declare functions, variables, and classes directly at the file level โ€” no enclosing class required. This is a major difference from Java.

Top-Level Function vs Class Function

kotlin
// Top-level function โ€” no class needed
fun double(n: Int) = n * 2

fun main() {
    println(double(7))
}
Output
14

double() is a top-level function. In Java, this would need to be a static method inside a class. Kotlin has no such requirement.

Multiple Files

In a real project, you split code across multiple .kt files. Each file can have its own package declaration. Files in the same package can access each other's top-level declarations without importing.

Practice Exercise

Exercisemultiple choice

Which statement about Kotlin top-level functions is true?

Quick Quiz

Quick Quiz

What comes first in a Kotlin file (if present)?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-01Kotlin 2.0

Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review