Introduction
Kotlin is a modern and mature programming language aimed to simplify developers' lives. It's concise, interoperable, safe with Java and other languages, and provides many ways to reuse code between multiple platforms for productive programming. If this is not your first language, you will grab things faster. But if you are a beginner, then do not worry. It is going to be fun learning Kotlin fundamentals here. To use Kotlin Online, you can check out Kotlin Playground.
Here are some of the important fundamental concepts of Kotlin,
Program entry point
An entry point of a Kotlin application is the same as the Java main
function.
fun main() {
println("Hello world!")
}
Variables and Data Types
Kotlin has a smart variable called val & var.
The term val defines local variables that can only be read. They can only have one value set to them.
val a: Int = 1 // immediate assignment
val b = 2 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 3 // deferred assignment
The var keyword is used to refer to reassignable variables.
var x = 5 // `Int` type is inferred
x += 1
Functions
A huge program can be divided into manageable, modular portions using functions. For example - you can define a function that calculates the product's price and calls it every time you need the calculation. Hence, it makes code reusable and prevents repetition.
fun sum(a: Int, b: Int): Int {
return a + b
}
Creating classes and instances
The class keyword should be used to define a class.
class Rectangle(var height: Double, var length: Double) {
var perimeter = (height + length) * 2
}
Comments
Kotlin allows both single-line (or end-of-line) and multi-line (block) comments, just like most contemporary languages.
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
/* The comment starts here
/* contains a nested comment */
and ends here. */
String templates
String templates make the code more readable and concise. See the below examples,
var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
Conditional expressions
Conditional expressions make your conditional statement written as an expression and in a more shorthand type. See the below example,
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
It can also be used as an expression in Kotlin.
fun maxOf(a: Int, b: Int) = if (a > b) a else b
You can easily find how it can be more helpful.
For loop
For loops are used in Kotlin to iterate across ranges, arrays, maps, and other types of data (anything that provides an iterator).
Kot lin's for-loop syntax is as follows:
for (item in collection) {
// loop body
}
While loop
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
When expression
You can think of Kotlin's when constructing as the Java switch statement's replacement. It compares a piece of code to many options.
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
Ranges
Kotlin lets you easily create ranges of values using the rangeTo()
function from the kotlin.ranges
package and its operator form ..
. Usually, rangeTo()
is complemented by in
or !in
functions.
Iterate over a range.
if (i in 1..4) { // equivalent of i >= 1 && i <= 4
print(i)
}
Or over a progression.
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
Collections
Kotlin also introduced the idea of collections, much like Java Collections. A collection typically includes several things of the same sort, referred to as elements or items in the collection. A wide range of utilities is available in the Kotlin Standard Library for managing collections.
Iterate over a collection.
for (item in items) {
println(item)
}
Check if a collection contains an object using in
operator.
when {
"orange" in items -> println("very juicy")
"apple" in items -> println("apple is good for health too")
}
Using lambda expressions to filter and map collections:
al fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }
Nullable values and null checks
When a null value is feasible, a reference must be explicitly designated as nullable. Names of nullable types end in '?'. So if you see the '?' after any var or val, this means it can contain null. See Null-safety for more info.
If str doesn't contain an integer, return null:
fun parseInt(str: String): Int? {
// ...
}
Type checks and automatic casts
The is operator determines whether an expression is a type instance. There is no need to explicitly cast an immutable local variable or property if it is checked for a certain type:
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}
// `obj` is still of type `Any` outside of the type-checked branch
return null
}
Here are some more points to remember about Kotlin,
Variables and Data Types
Variables are used to store values in Kotlin. The data types available in Kotlin include numbers (Int, Double, Float, etc.), characters (Char), Boolean values (Boolean), and strings (String).
Functions
Functions are used to encapsulate a block of code and can accept parameters and return values. In Kotlin, functions are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned as values from functions.
Control Flow
Kotlin has all the typical control flow structures in programming languages, including if/else statements, for loops, while loops, and when expressions.
Null Safety
Kotlin provides null safety features to help prevent null pointer exceptions. It does this by distinguishing between nullable and non-nullable types, forcing developers to explicitly handle null values.
Object-Oriented Programming (OOP)
Kotlin supports OOP concepts like classes, inheritance, interfaces, and abstract classes. It also has additional features like data classes, which can be used to create classes that only hold data.
Extension Functions
Kotlin allows developers to extend existing classes with new functionality using extension functions. This allows for creating utility functions that can be used across an application.
Coroutines
Coroutines are a feature in Kotlin that allow for asynchronous programming. They can be used to simplify complex asynchronous code and can be used with many different concurrency models.
Conclusion
Overall, Kotlin is a powerful, expressive language with many features that make it a great choice for modern software development. Feel free to ask for any suggestions. I hope you like the article. You can also check out my latest article, What's new in Android Studio.
Please keep checking back since I will soon provide another article on Kotlin. Enjoy reading the other articles until then.