Kotlin Syntax
Welcome to the world of Kotlin! In this guide, we'll explore the basic syntax elements of the Kotlin programming language. Understanding these fundamentals is essential for building any Kotlin application, whether it's for Android development, server-side applications, or other purposes.
Introduction
Kotlin is a modern, statically-typed programming language that runs on the Java Virtual Machine (JVM). It combines object-oriented and functional programming features, and it's designed to be more concise, safer, and more expressive than Java while maintaining full interoperability.
Before diving into complex applications, let's first understand the basic building blocks of Kotlin code.
Program Entry Point
Unlike many other programming languages, Kotlin doesn't require a class to start with. Your program can begin with a main
function, which serves as the entry point.
fun main() {
println("Hello, Kotlin!")
}
Output:
Hello, Kotlin!
You can also define the main function with command-line arguments:
fun main(args: Array<String>) {
println("Hello, ${args.getOrNull(0) ?: "Kotlin"}!")
}
Variables and Constants
Kotlin provides two main ways to declare variables: var
for mutable variables and val
for immutable variables (constants).
Using var
(Mutable)
fun main() {
var name = "John"
println("Name: $name")
name = "Jane" // Value can be changed
println("Updated name: $name")
}
Output:
Name: John
Updated name: Jane
Using val
(Immutable)
fun main() {
val pi = 3.14159
println("Pi value: $pi")
// pi = 3.14 // Error: Val cannot be reassigned
}
Output:
Pi value: 3.14159
Type Declaration
Kotlin features type inference, which means it can often determine the type automatically. However, you can also specify the type explicitly:
fun main() {
val name: String = "Alice"
val age: Int = 30
val height: Double = 5.9
val isStudent: Boolean = true
println("Name: $name, Age: $age, Height: $height, Is Student: $isStudent")
}
Output:
Name: Alice, Age: 30, Height: 5.9, Is Student: true
Basic Data Types
Kotlin provides several built-in data types:
- Numbers:
Int
,Long
,Float
,Double
,Short
,Byte
- Characters:
Char
- Strings:
String
- Booleans:
Boolean
- Arrays:
Array
fun main() {
val intValue: Int = 10
val longValue: Long = 100L
val floatValue: Float = 3.14f
val doubleValue: Double = 3.14159
val charValue: Char = 'A'
val stringValue: String = "Hello"
val booleanValue: Boolean = true
val intArray: Array<Int> = arrayOf(1, 2, 3, 4, 5)
println("Integer: $intValue")
println("Long: $longValue")
println("Float: $floatValue")
println("Double: $doubleValue")
println("Character: $charValue")
println("String: $stringValue")
println("Boolean: $booleanValue")
println("Array: ${intArray.joinToString()}")
}
Output:
Integer: 10
Long: 100
Float: 3.14
Double: 3.14159
Character: A
String: Hello
Boolean: true
Array: 1, 2, 3, 4, 5
String Templates
Kotlin makes string interpolation easy using string templates:
fun main() {
val name = "Kotlin"
val year = 2016
// Simple variable reference
println("$name was officially released in $year")
// Expression in string template
println("${name.length} characters in the name $name")
// Complex expressions
println("In 10 years, it will be ${year + 10}")
}
Output:
Kotlin was officially released in 2016
6 characters in the name Kotlin
In 10 years, it will be 2026
Control Flow
Conditional Statements
Kotlin provides standard if-else
statements, but they can also be used as expressions:
fun main() {
val age = 20
// If-else as a statement
if (age >= 18) {
println("You are an adult")
} else {
println("You are a minor")
}
// If-else as an expression
val status = if (age >= 18) "adult" else "minor"
println("Status: $status")
}
Output:
You are an adult
Status: adult
When Expression
The when
expression is Kotlin's equivalent of the switch statement, but much more powerful:
fun main() {
val dayOfWeek = 3
val day = when (dayOfWeek) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
println("Day $dayOfWeek is $day")
// When with multiple values per branch
val numberType = when (dayOfWeek) {
1, 3, 5, 7 -> "Odd day number"
2, 4, 6 -> "Even day number"
else -> "Invalid day"
}
println("$day is an $numberType")
}
Output:
Day 3 is Wednesday
Wednesday is an Odd day number
Loops
For Loop
fun main() {
// Range-based for loop
println("Counting from 1 to 5:")
for (i in 1..5) {
print("$i ")
}
println()
// Iterate over an array
val fruits = arrayOf("Apple", "Banana", "Cherry", "Date")
println("Fruit list:")
for (fruit in fruits) {
println("- $fruit")
}
// With index
println("Indexed fruits:")
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
}
Output:
Counting from 1 to 5:
1 2 3 4 5
Fruit list:
- Apple
- Banana
- Cherry
- Date
Indexed fruits:
0: Apple
1: Banana
2: Cherry
3: Date
While and Do-While Loops
fun main() {
var counter = 5
println("While loop:")
while (counter > 0) {
print("$counter ")
counter--
}
println()
// Reset counter
counter = 5
println("Do-While loop:")
do {
print("$counter ")
counter--
} while (counter > 0)
println()
}
Output:
While loop:
5 4 3 2 1
Do-While loop:
5 4 3 2 1
Functions
Functions in Kotlin are declared using the fun
keyword:
// Simple function
fun greet() {
println("Hello, world!")
}
// Function with parameters
fun greetPerson(name: String) {
println("Hello, $name!")
}
// Function with return value
fun sum(a: Int, b: Int): Int {
return a + b
}
// Single-expression function
fun multiply(a: Int, b: Int): Int = a * b
// Function with default parameter values
fun introduce(name: String, age: Int = 30) {
println("Hi, I'm $name and I'm $age years old")
}
fun main() {
greet()
greetPerson("Alice")
val result1 = sum(5, 3)
println("5 + 3 = $result1")
val result2 = multiply(4, 2)
println("4 × 2 = $result2")
introduce("Bob")
introduce("Charlie", 25)
}
Output:
Hello, world!
Hello, Alice!
5 + 3 = 8
4 × 2 = 8
Hi, I'm Bob and I'm 30 years old
Hi, I'm Charlie and I'm 25 years old
Comments
Kotlin supports single-line and multi-line comments, similar to Java:
// This is a single-line comment
/*
This is a multi-line comment
spanning multiple lines
*/
/**
* This is a KDoc comment (Kotlin's version of JavaDoc)
* Used for documenting code
* @param name The name to greet
* @return A greeting message
*/
fun generateGreeting(name: String): String {
return "Welcome, $name!"
}
fun main() {
val message = generateGreeting("Developer")
println(message)
}
Output:
Welcome, Developer!
Nullable Types
One of Kotlin's key features is its approach to handling null values:
fun main() {
// Non-nullable type
var nonNullName: String = "John"
// nonNullName = null // Compilation Error
// Nullable type (with question mark)
var nullableName: String? = "John"
nullableName = null // OK
// Safe call operator
println(nullableName?.length) // Prints null if nullableName is null
// Elvis operator (provide default value if null)
val length = nullableName?.length ?: 0
println("Length is: $length")
// Non-null assertion operator (throws exception if null)
// Use this only when you're absolutely sure the value isn't null
val anotherName: String? = "Alice"
println("Definitely not null length: ${anotherName!!.length}")
}
Output:
null
Length is: 0
Definitely not null length: 5
Real-World Example: Simple Contact Manager
Let's apply these syntax elements to create a simple contact manager application:
// Define a data class for contacts
data class Contact(
val name: String,
val email: String,
var phoneNumber: String? = null
)
// Manage a list of contacts
class ContactManager {
private val contacts = mutableListOf<Contact>()
fun addContact(contact: Contact) {
contacts.add(contact)
println("Added new contact: ${contact.name}")
}
fun displayContacts() {
if (contacts.isEmpty()) {
println("No contacts available")
return
}
println("\nContact List:")
for ((index, contact) in contacts.withIndex()) {
val phone = contact.phoneNumber ?: "N/A"
println("${index + 1}. ${contact.name} (${contact.email}) - Phone: $phone")
}
}
fun searchContact(query: String): List<Contact> {
val results = contacts.filter {
it.name.contains(query, ignoreCase = true) ||
it.email.contains(query, ignoreCase = true) ||
(it.phoneNumber != null && it.phoneNumber!!.contains(query))
}
return results
}
}
// Main function to demonstrate the contact manager
fun main() {
val manager = ContactManager()
// Add some contacts
manager.addContact(Contact("Alice Smith", "[email protected]", "123-456-7890"))
manager.addContact(Contact("Bob Johnson", "[email protected]"))
manager.addContact(Contact("Charlie Brown", "[email protected]", "555-123-4567"))
// Display all contacts
manager.displayContacts()
// Search for contacts
val searchQuery = "Ali"
val results = manager.searchContact(searchQuery)
println("\nSearch results for '$searchQuery':")
if (results.isEmpty()) {
println("No contacts found")
} else {
for (contact in results) {
val phone = contact.phoneNumber ?: "N/A"
println("${contact.name} (${contact.email}) - Phone: $phone")
}
}
}
Output:
Added new contact: Alice Smith
Added new contact: Bob Johnson
Added new contact: Charlie Brown
Contact List:
1. Alice Smith ([email protected]) - Phone: 123-456-7890
2. Bob Johnson ([email protected]) - Phone: N/A
3. Charlie Brown ([email protected]) - Phone: 555-123-4567
Search results for 'Ali':
Alice Smith ([email protected]) - Phone: 123-456-7890
Summary
In this guide, we've covered the fundamental syntax elements of Kotlin:
- Program structure and entry points
- Variables and constants using
var
andval
- Basic data types
- String templates for easy interpolation
- Control flow with
if-else
andwhen
expressions - Loops including
for
,while
, anddo-while
- Function declaration and usage
- Comments for documenting code
- Handling null values with Kotlin's nullable types
- A real-world example showing these concepts in practice
Kotlin's syntax is designed to be concise, expressive, and safe, eliminating many common programming errors while still being familiar to developers with Java experience.
Additional Resources
Here are some resources to further explore Kotlin syntax:
- Official Kotlin Documentation
- Kotlin Koans - Interactive coding exercises
Practice Exercises
- Create a temperature converter that converts between Celsius and Fahrenheit.
- Write a program that checks if a year is a leap year.
- Create a simple calculator that performs basic arithmetic operations.
- Implement a function that reverses a string without using built-in reverse functions.
- Create a shopping list application that allows adding, removing, and displaying items.
Happy coding with Kotlin!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)