Now that you know what Kotlin is and why it’s a great choice for mobile development, it’s time to roll up our sleeves and dive into the basics of the language. Whether you’re transitioning from Java or just starting out in mobile development, understanding Kotlin’s basic syntax is the foundation for writing clean, efficient code.
In this article, we’ll cover key aspects of Kotlin’s syntax, from declaring variables to writing functions and control flow statements. Let’s get started!
Variables in Kotlin
In Kotlin, variables can be declared in two ways: as val
or var
. This is one of the first things you’ll need to get used to, as it’s different from Java’s variable declaration.
val
: Immutable, meaning the value assigned to it cannot be changed (like a constant in other languages).var
: Mutable, meaning the value can change after it’s been assigned.
Example:
val name: String = "John" // Immutable variable
var age: Int = 25 // Mutable variable
Here, name
is a constant and cannot be reassigned, whereas age
can be changed. Kotlin is a statically typed language, so each variable has a type, but it can be inferred automatically:
val country = "Canada" // Type inferred as String
var score = 100 // Type inferred as Int
Functions in Kotlin
Defining a function in Kotlin is straightforward and compact. Functions are declared using the fun
keyword, followed by the function name, parameters (if any), and the return type (if applicable).
Example:
fun greet(name: String): String {
return "Hello, $name!"
}
Here, greet
takes a parameter name
of type String
and returns a String
. Kotlin allows string interpolation, so you can insert variable values directly into a string using the $
symbol, making the code clean and readable.
Function with Default Parameter:
Kotlin allows default parameter values, which can be useful for simplifying your code.
fun greet(name: String = "Guest"): String {
return "Hello, $name!"
}
If no name is passed when calling the function, it will use the default value "Guest"
.
Control Flow in Kotlin
Kotlin has all the standard control flow statements you’re probably familiar with from other languages, like if
, when
, for
, and while
. However, they come with a few enhancements that make them more powerful and easier to use.
if
Expressions
In Kotlin, if
is an expression, meaning it can return a value. This eliminates the need for ternary operators.
val max = if (a > b) a else b
The if
expression here returns either a
or b
, depending on the condition.
when
Expression
The when
expression in Kotlin is like Java’s switch
, but more powerful and flexible. It allows you to handle multiple cases in a clean way.
fun getStatusCode(code: Int): String {
return when (code) {
200 -> "OK"
404 -> "Not Found"
500 -> "Internal Server Error"
else -> "Unknown Code"
}
}
Notice that when
can return a value, and there’s no need to add break
statements as in Java.
Loops in Kotlin
Kotlin supports all the common loop structures like for
, while
, and do-while
. Let’s look at each one.
for
Loop
Kotlin’s for
loop is used to iterate over ranges, arrays, or collections. The syntax is concise and easy to understand.
for (i in 1..5) {
println(i)
}
This prints the numbers 1 through 5. The 1..5
syntax represents a range from 1 to 5, inclusive.
You can also loop through an array or list:
val items = listOf("apple", "banana", "orange")
for (item in items) {
println(item)
}
while
and do-while
Loops
while
and do-while
loops function similarly to other languages.
while
Loop Example:
var i = 1
while (i <= 5) {
println(i)
i++
}
do-while
Loop Example:
var j = 1
do {
println(j)
j++
} while (j <= 5)
The do-while
loop guarantees that the block of code will execute at least once, even if the condition is false from the start.
Null Safety in Kotlin
One of the standout features of Kotlin is its built-in null safety, which eliminates the risk of null pointer exceptions.
In Kotlin, types are non-nullable by default. If you want to allow a variable to hold a null
value, you need to explicitly mark the type as nullable using the ?
symbol.
Example:
var name: String? = null // Nullable String
To safely access a nullable variable, Kotlin provides the ?.
operator, which only calls a method if the variable is not null.
val length = name?.length
If name
is null
, length
will also be null
, but no exception will be thrown.
You can also use the Elvis operator (?:
) to provide a default value in case of a null:
val length = name?.length ?: 0
If name
is null, length
will be assigned a value of 0
.
Classes and Objects in Kotlin
Kotlin is an object-oriented language, which means you’ll be working with classes and objects to structure your code.
Defining a Class:
class Person(val firstName: String, val lastName: String) {
fun getFullName(): String {
return "$firstName $lastName"
}
}
Here, Person
is a class with two properties: firstName
and lastName
. The getFullName
method combines these two properties into a full name.
Creating an Object:
val person = Person("John", "Doe")
println(person.getFullName()) // Output: John Doe
Data Classes
In Kotlin, data classes are used to store data. These classes automatically provide toString()
, equals()
, hashCode()
, and copy()
methods, so you don’t have to write boilerplate code.
data class User(val name: String, val age: Int)
With this simple declaration, Kotlin gives you everything you need to work with User
objects.
Conclusion
Now that you have a basic understanding of Kotlin’s syntax, you’re well on your way to writing clean, concise, and efficient code. Kotlin’s features like null safety, concise syntax, and expressive control flow make it a pleasure to work with, especially in mobile development.
Are you ready to explore more? Keep practicing the basics, and soon you’ll find yourself building your own mobile apps with ease!
Next up: Kotlin Functions in Depth: How to Work with Functions and Lambdas in Kotlin.