Kotlin Tutorial menu

Kotlin Introduction

Kotlin is a modern, safe and easy-to-read programming language, used most for Android apps.

What is Kotlin?

  • Kotlin was created by JetBrains and released in 2016
  • In 2019 Google announced that Kotlin is the preferred language for Android
  • Kotlin runs on the JVM (Java Virtual Machine), so it works with all Java libraries
  • Kotlin code is shorter than Java code and protects you from many errors

Where is Kotlin Used?

AreaExample
Android appsFood delivery, banking and shopping apps
Server sideWeb APIs with Ktor or Spring Boot
DesktopPrograms built with Compose for Desktop
MultiplatformSharing code between Android and iPhone apps

How to Run Kotlin

You have two easy choices:

  1. Kotlin Playground: an online editor at play.kotlinlang.org. Nothing to install.
  2. IntelliJ IDEA or Android Studio: free editors from JetBrains and Google. Create a new Kotlin project and write code in a file that ends with .kt.

For this tutorial the online Playground is enough. You will need Android Studio later when you start building apps.

Your First Program

Example

kotlin
fun main() {
    println("Hello, Workownix!")
}
Output
Hello, Workownix!

The example explained

CodeMeaning
funStarts a function
main()The function where every Kotlin program starts
{ }Curly braces hold the code of the function
println()Prints text and then moves to a new line
"Hello, Workownix!"A string: text inside double quotes

Unlike Java, you do not need a semicolon at the end of each line.

println() adds a new line after the text. print() does not, so the next output continues on the same line.

Example

kotlin
fun main() {
    print("Karachi ")
    print("is a big city. ")
    println("It is by the sea.")
    println(5 + 3)
    println("5 + 3")
}
Output
Karachi is a big city. It is by the sea.
8
5 + 3

Notice the difference: 5 + 3 without quotes is a calculation, so Kotlin prints 8. With quotes it is just text.

Comments

Comments are notes for people who read your code. Kotlin ignores them.

Example

kotlin
fun main() {
    // This is a single-line comment
    println("Comments are not printed") // a comment at the end of a line

    /* This comment
       can span many lines */
}
Output
Comments are not printed

Exercise

Exercise

Which function is the starting point of every Kotlin program?

Learn Kotlin with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp