Kotlin basics for Android (Part-1)
4 min readApr 10, 2023
Kotlin was introduced as a statically-typed programming language for the Java Virtual Machine (JVM) with the goal of addressing some of the pain points and limitations of Java, which is the primary programming language used for Android app development.
Main Reasons for introducing Kotlin :
- Modern Language Features: Kotlin was designed to be a modern, expressive, and more concise language compared to Java, with features such as lambda expressions, extension functions, null safety, and improved type inference. These language features allow developers to write more efficient and expressive code, reducing boilerplate and improving productivity.
- Interoperability with Java: Kotlin was designed to be fully interoperable with Java, which means that Kotlin code can seamlessly coexist with Java code in the same project, and Kotlin can call Java code and vice versa without any interoperability issues. This makes Kotlin a good choice for existing Java projects and enables a smooth transition from Java to Kotlin.
- Safety and Nullability: Kotlin places a strong emphasis on null safety, which helps to prevent null pointer exceptions (NPEs) that are common in Java. Kotlin’s type system distinguishes between nullable and non-null types, making it clear when a value can be null and when it cannot. This helps to write more robust and safer code.
- Developer Productivity: Kotlin was designed to improve developer productivity by reducing boilerplate, providing a more concise and expressive syntax, and offering powerful features like extension functions, which can simplify common tasks. Kotlin’s interoperability with Java also allows developers to reuse existing Java code and libraries, making it easier to adopt Kotlin in existing projects.
- Official Android Support: Kotlin was officially endorsed by Google as a first-class language for Android app development at the Google I/O conference in 2017. This endorsement brought significant attention and support to Kotlin from the Android development community, making it a popular choice for new Android projects.
Basic Concepts of Kotlin
- Kotlin Extensions: Kotlin provides a feature called “extensions” that allows you to add new functions or properties to existing classes without modifying their source code. This can be handy for adding utility methods or simplifying common tasks.
// Extension function to capitalize the first letter of a String
fun String.capitalizeFirstLetter(): String {
return this.replaceFirstChar { it.uppercase() }
}
val name = "john"
val capitalized = name.capitalizeFirstLetter() // Call the extension function
- Null Safety: Kotlin has a strong emphasis on null safety, helping to prevent null pointer exceptions (NPEs) that are common in Java. Kotlin enforces strict nullability rules, making it clear when a value can be null and when it cannot. This is achieved through nullable and non-null types, safe call (
?.
) and elvis operator (?:
).
val name: String? = null // Nullable variable
val length = name?.length // Safe call to get the length, returns null if name is null
val upperCaseName = name?.toUpperCase() ?: "Unknown" // Elvis operator for null value handling
- Lambda Expressions: Kotlin supports concise and expressive lambda expressions, which are anonymous functions that can be used for passing behavior as parameters to other functions, such as in functional programming and event handling.
val numbers = listOf(1, 2, 3, 4, 5)
// Using a lambda expression to filter and map a list of numbers
val evenSquares = numbers.filter { it % 2 == 0 }.map { it * it }
- Data Classes: Kotlin provides data classes that automatically generate common boilerplate code for modelling data, such as equals(), hashCode(), toString(), and copy(). Data classes are often used for representing data in Android apps, such as model classes for API responses or local data storage.
data class User(val id: Int, val name: String, val age: Int)
val user1 = User(1, "Alice", 25)
val user2 = User(1, "Alice", 25)
println(user1 == user2) // Prints true, as data classes automatically implement equals()
- Extension Properties: Kotlin allows you to define extension properties, which are similar to extension functions but allow you to add properties to existing classes.
// Extension property to get the length of a List
val <T> List<T>.length: Int
get() = this.size
val numbers = listOf(1, 2, 3, 4, 5)
val length = numbers.length // Call the extension property
- Functions: Kotlin supports defining functions, which can be standalone or part of classes. Functions can have parameters, return values, and can be used for various purposes, such as event handling, data processing, and more.
fun greet(name: String): String {
return "Hello, $name!"
}
val greeting = greet("Alice") // Function call
- Classes and Inheritance: Kotlin supports object-oriented programming (OOP) concepts, including classes, objects, interfaces, and inheritance. Kotlin uses the
class
keyword to define classes and theobject
keyword to define singleton objects.
class Person(val name: String, val age: Int) {
fun sayHello() {
println("Hello, my name is $name and I am $age years old!")
}
}
val person = Person("Bob", 30)
person.sayHello()
- Control Flow: Kotlin supports various control flow statements, such as
if
,when
,for
, andwhile
, which are used to implement logic and flow control in your app.
val score = 85
if (score >= 90) {
println("Excellent!")
} else if (score >= 70) {
println("Good job!")
} else {
println("Keep it up!")
}
when (score) {
in 90..100 -> println("You got an A+!")
in 80..89 -> println("You got an A!")
in 70..79 -> println("You got a B!")
else -> println("You got a C or below.")
}
for (i in 1..5) {
println("Number: $i")
}
var count = 0
while (count < 3) {
println("Count: $count")
count++
}