Hello Kotlin: main and tooling

Kotlin · Essentials · 8 min

Getting a program running is the first step, and Kotlin projects are almost always built with Gradle.

A Kotlin program starts at a top-level main function; no class is required:

fun main() { println("Hello, Kotlin!") }

If you need command-line arguments, declare fun main(args: Array<String>). Statements don't need semicolons, and println / print write to standard output; readln() reads a line from standard input.

Ways to run Kotlin:

  • IntelliJ IDEA (made by JetBrains, Kotlin's creator) or Android Studio: click the run gutter icon next to main.
  • Gradle with the Kotlin JVM plugin, the standard for real projects: ./gradlew run. Build scripts themselves are often written in Kotlin (build.gradle.kts).
  • The command-line compiler: kotlinc hello.kt -include-runtime -d hello.jar then java -jar hello.jar.
  • Scripts (.main.kts) and the online Kotlin Playground for quick experiments.

Kotlin compiles to JVM bytecode, so a Kotlin app is a normal Java application and can use any Java library. The same language also targets JavaScript, WebAssembly and native binaries through Kotlin Multiplatform.

Files contain top-level functions, properties and classes, optionally in a package. A file Main.kt with top-level functions compiles to a JVM class named MainKt.

Example

// Main.kt  - run with: kotlinc Main.kt -include-runtime -d app.jar && java -jar app.jar
fun main(args: Array<String>) {
    println("Hello, Kotlin!")          // Hello, Kotlin!
    println("Args: ${args.size}")      // Args: 0
    val name = "Ada"
    print("Hi, ")
    println(name)                      // Hi, Ada
}

Remember

  • Programs start at a top-level fun main()
  • Real projects build with Gradle; IntelliJ IDEA is the main IDE
  • Kotlin compiles to JVM bytecode and uses Java libraries directly

Check yourself

  1. What does a Kotlin file Main.kt with top-level functions compile to on the JVM?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kotlinlang.org/docs/getting-started.html

Builds on

Nothing: this is a foundation.

Unlocks