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?
| Area | Example |
|---|---|
| Android apps | Food delivery, banking and shopping apps |
| Server side | Web APIs with Ktor or Spring Boot |
| Desktop | Programs built with Compose for Desktop |
| Multiplatform | Sharing code between Android and iPhone apps |
How to Run Kotlin
You have two easy choices:
- Kotlin Playground: an online editor at play.kotlinlang.org. Nothing to install.
- 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
fun main() {
println("Hello, Workownix!")
}Hello, Workownix!
The example explained
| Code | Meaning |
|---|---|
fun | Starts 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.
print and println
println() adds a new line after the text. print() does not, so the next output continues on the same line.
Example
fun main() {
print("Karachi ")
print("is a big city. ")
println("It is by the sea.")
println(5 + 3)
println("5 + 3")
}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
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 */
}Comments are not printed
Exercise
Exercise
Which function is the starting point of every Kotlin program?
