Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 15 / Topic 1 of 6

What kotlinc actually generates

Every .kt file compiles to one or more real JVM .class files. A class you write becomes an ordinary class. Top-level functions and main() have nowhere to live in the JVM's class-based world, so the compiler invents one: a final class named after the file, with every top-level function turned into a static method on it.

class Shipment(val id: String, var weightKg: Double)

fun describe(shipment: Shipment): String = "${shipment.id} weighs ${shipment.weightKg} kg"

fun main() {
    val shipment = Shipment("S-2001", 1200.0)
    println(describe(shipment))
}

Compile it and look inside with javap (-p shows private members too; without it, private things are hidden):

$ kotlinc 01_what_kotlinc_generates.kt -d out
$ ls out
_01_what_kotlinc_generatesKt.class
META-INF
Shipment.class

$ javap -p out/Shipment.class
public final class Shipment {
  private final java.lang.String id;
  private double weightKg;
  public Shipment(java.lang.String, double);
  public final java.lang.String getId();
  public final double getWeightKg();
  public final void setWeightKg(double);
}

⚠️ A filename that starts with a digit (like 01_what_kotlinc_generates.kt, chosen to keep this part's examples numbered and ordered) can't become a legal Java class name as-is -- 01WhatKotlincGeneratesKt would start with a digit too. kotlinc fixes this by prefixing a leading underscore: the generated class is actually _01_what_kotlinc_generatesKt.class. This is purely a file-naming quirk of these lesson files; a normally named file like Hello.kt or Billing.kt produces exactly HelloKt.class / BillingKt.class, no underscore.

Shipment is final (Kotlin classes are final unless marked open), and id/weightKg are private with public accessor methods generated for you -- section 2 covers exactly how those are built. describe and main live as static methods on the generated file class, which you can confirm the same way: javap -p out/_01_what_kotlinc_generatesKt.class.

Full program: examples/01_what_kotlinc_generates.kt.

Done here? The practice set for Part 15 — including the solutions — is on the part page.

Search the guide