Your First Kotlin Program

Kotlin · Lesson 3 of 29 7 min read Updated

Every Kotlin program, from a two-line greeting to a large Android app, is made of the same basic pieces: functions, statements and values. In this lesson you will write small programs, understand every word in them, print text in different ways, add comments and read what the user types.

Type the examples yourself in IntelliJ IDEA or the Kotlin Playground. Typing, making small mistakes and fixing them teaches you much more than reading.

The main function

When a Kotlin program starts, it looks for a function named main and runs the code inside it, from top to bottom.

Kotlin
fun main() {
    print("Rohtak ")
    print("to ")
    println("Delhi")
    println("Distance: about 70 km")
    println()
    println("Have a safe journey!")
}
Output
Rohtak to Delhi
Distance: about 70 km

Have a safe journey!

Here is what each part means:

  • fun starts a function, a named block of code.
  • main is the function's name. The name main is special: it is the starting point.
  • () holds the function's parameters. This main has none.
  • { and } mark the start and end of the function body.
  • println prints its text and then moves to a new line. print prints without the line break, so the next output continues on the same line. println() with nothing inside prints an empty line.

Unlike Java, Kotlin does not need a class around main. A function written directly in a file, outside any class, is called a top-level function.

Each line inside the body is a statement, an instruction to do something. You do not end statements with semicolons. You only need a semicolon if you put two statements on one line, which is rarely a good idea.

Escape characters

Text inside double quotes is called a string. Some characters cannot be typed directly inside a string, so you write them with a backslash. This is called an escape sequence.

EscapeMeaning
\nnew line
\ttab
\"a double quote
\\a backslash
\$a dollar sign that is not a template
Kotlin
fun main() {
    println("She said \"Kotlin is fun\"")
    println("Folder: C:\\kotlinc\\bin")
    println("Write \$city to insert a value")
    println("Line one\nLine two")
}
Output
She said "Kotlin is fun"
Folder: C:\kotlinc\bin
Write $city to insert a value
Line one
Line two

The dollar sign needs care because $ starts a string template (you saw $city in the previous lesson). Writing \$ prints a plain $.

Comments

Comments are notes for humans. The compiler ignores them. Use them to explain why something is done, not to repeat what the code obviously says.

Kotlin
// A single-line comment starts with two slashes.

/*
   A block comment can span
   several lines.
*/

/**
 * A documentation comment (KDoc) describes the function below it.
 * Editors show this text when you hover over the function name.
 */
fun main() {
    println("Hello") // a comment can also follow code
    // println("This line is switched off")
}
Output
Hello

Putting // in front of a line of code is a quick way to switch it off while testing. Kotlin also allows block comments inside other block comments, which Java does not.

Calling your own functions

You can write more top-level functions and call them from main. You will learn functions properly later; for now, see how one function can use another.

Kotlin
fun printHeader() {
    println("==== Meera's Bakery, Kochi ====")
}

fun main() {
    printHeader()
    println("Plum cake: Rs 450")
    println("Banana chips: Rs 120")
    printHeader()
}
Output
==== Meera's Bakery, Kochi ====
Plum cake: Rs 450
Banana chips: Rs 120
==== Meera's Bakery, Kochi ====

printHeader() runs the code inside that function each time you call it. The order of functions in the file does not matter: main can call a function written above or below it.

Reading input with readln

readln() waits for the user to type a line and press Enter, then gives you that line as a string. To get a number, convert the text with toInt() or toDouble().

Kotlin
fun main() {
    print("Enter your name: ")
    val name = readln()
    print("How many tickets? ")
    val tickets = readln().toInt()
    println("Booked $tickets tickets for $name.")
    println("Total: Rs ${tickets * 250}")
}

A run where the user types Aarav and 3:

Output
Enter your name: Aarav
How many tickets? 3
Booked 3 tickets for Aarav.
Total: Rs 750

${tickets * 250} puts the result of a calculation into the text. If the user types three instead of 3, toInt() fails with a NumberFormatException and the program stops. You will learn safe ways to handle this in Null Safety and Exceptions & Error Handling.

Program arguments

main can also accept the words typed after the program name on the command line. These arrive as an Array<String> named args.

Kotlin
fun main(args: Array<String>) {
    println("You passed ${args.size} arguments")
    println("First city: ${args[0]}")
}
Terminal
java -jar trip.jar Jaipur Udaipur
Output
You passed 2 arguments
First city: Jaipur

Most programs in this course use plain fun main(). Use the args version only when you need command-line arguments.

Common mistakes

  • Wrong capital letters. Kotlin is case-sensitive: Println or Main will not work. The compiler reports an "Unresolved reference" error for names it does not know.
  • Curly quotes. Copying code from a word processor can turn " into “. Kotlin needs straight quotes.
  • Missing closing brace. Every { needs a matching }. Good indentation (four spaces) makes this easy to see.
  • Forgetting the brackets on calls. printHeader without () does not call the function.

Key points

  • A program starts at fun main(); it needs no class around it.
  • println prints a line; print prints without moving to a new line.
  • Escape sequences like \n, \", \\ and \$ put special characters in strings.
  • //, /* */ and /** */ write comments; the compiler ignores them.
  • readln() reads a line of input as a string; convert it with toInt() or toDouble().
  • fun main(args: Array<String>) receives command-line arguments.

Exercise

Write a program for Isha's tuition centre. It should print a header line, ask for the student's name and the number of months they want to join for, and then print a message with the total fee at Rs 1,200 per month. Add a comment that explains the fee rate.

Show solution
Kotlin
fun main() {
    println("--- Isha's Tuition Centre ---")
    print("Student name: ")
    val name = readln()
    print("Months: ")
    val months = readln().toInt()
    // The monthly fee is fixed at Rs 1200 for all classes.
    println("$name, your fee for $months months is Rs ${months * 1200}.")
}

A run where the user types Kabir and 4:

Output
--- Isha's Tuition Centre ---
Student name: Kabir
Months: 4
Kabir, your fee for 4 months is Rs 4800.

readln().toInt() turns the typed text into a number so you can multiply it.

Quick Quiz

1. What is the difference between print and println?

2. How do you print a double quote inside a string?

3. What does readln() return?

4. Does a Kotlin main function need to be inside a class?

Learn Kotlin with a mentor

Free lessons get you started. Our Programming & Software Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call