Kotlin is a modern, statically typed, and multiplatform programming language designed to be fully interoperable with Java.
It is primarily used for mobile application development on Android and for server-side application development.
Installation
Installing Kotlin
To install Kotlin, you can use the Kotlin SDK or set up the environment in an IDE.
Verify installation
To check if Kotlin is correctly installed, you can run the following command:
kotlin -version
Variables and Data Types
Declaring Variables
Kotlin allows declaring mutable (var
) and immutable (val
) variables.
val name: String = "Luis" // immutable
var age: Int = 10 // mutable
Kotlin can infer the type automatically, but it can also be specified.
Data Types
Kotlin supports several basic data types.
Type | Description |
---|---|
Int | Integer numbers |
Double | Floating-point numbers |
Boolean | True or false values |
String | Text strings |
val integer: Int = 10
val text: String = "Hello, Kotlin"
val isActive: Boolean = true
Type Conversion
In Kotlin, type conversions are not implicit. To convert types, specific functions must be used.
val number = 42
val numberAsString = number.toString() // "42"
val textAsInt = "10".toInt() // 10
Operators
slug: kotlin-cheatsheet-operators title: Kotlin Operators CheatSheet description: Brief CheatSheet on operators in Kotlin, including arithmetic, logical, and comparison operators.
Operators in Kotlin
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulo (remainder) | a % b |
Comparison Operators
Comparison operators are used to compare two values.
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
Logical Operators
Logical operators are used to combine boolean expressions.
Operator | Description | Example |
---|---|---|
&& | Logical AND | a && b |
` | ` | |
! | Negation | !a |
Assignment Operators
Assignment operators are used to assign values to variables.
Operator | Description | Example |
---|---|---|
= | Simple assignment | a = 5 |
+= | Addition and assignment | a += 3 |
-= | Subtraction and assignment | a -= 2 |
*= | Multiplication and assignment | a *= 4 |
/= | Division and assignment | a /= 2 |
%= | Modulo and assignment | a %= 3 |
Elvis Operator (?:)
The Elvis operator is used to handle null values concisely:
val result = a ?: 0 // If 'a' is null, assign 0
Operator Overloading
Kotlin allows overloading operators for custom classes.
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}
Control Structures
Conditionals
IF
Kotlin uses if
as an expression, meaning it can return a value.
val max = if (a > b) a else b
When
when
in Kotlin is an “enhanced” version of switch
. It allows handling multiple cases and returning values.
val result = when (x) {
1 -> "One"
2 -> "Two"
else -> "Another value"
}
Loops
FOR
Iterates over any collection or range.
for (i in 1..10) {
println(i)
}
While
while
and do-while
for conditional looping.
while (x < 5) {
println(x)
x++
}
Functions
Function Declaration
A function is defined with the keyword fun
. Parameters are required to have a type.
fun add(a: Int, b: Int): Int {
return a + b
}
Single-line Functions
If the function only has one expression, it can be defined concisely.
fun multiply(a: Int, b: Int) = a * b
Functions with Default Values
Default values can be assigned to parameters.
fun greet(name: String = "Guest") {
println("Hello, $name")
}
Higher-order Functions
Kotlin allows using functions as parameters.
fun performOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
// Usage
val sum = performOperation(5, 3, { x, y -> x + y })
Lambda Functions
Lambda functions are anonymous functions that can be assigned to variables or passed as parameters.
val sum = { a: Int, b: Int -> a + b }
println(sum(2, 3)) // 5
Extension Functions
Kotlin allows adding new functions to existing classes without modifying their code.
fun String.greet(): String {
return "Hello, $this"
}
// Usage of the extension function
val greeting = "Kotlin".greet()
Collections
Ranges
Kotlin has native support for ranges.
for (i in 1..5) println(i) // 1, 2, 3, 4, 5
for (i in 5 downTo 1) println(i) // 5, 4, 3, 2, 1
Lists
Lists can be mutable (MutableList
) or immutable (List
).
val immutableList = listOf(1, 2, 3)
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)
Maps
Maps can be mutable or immutable.
val map = mapOf("key1" to "value1", "key2" to "value2")
val mutableMap = mutableMapOf("key1" to "value1")
mutableMap["key3"] = "value3"
Sets
Sets do not allow duplicate elements.
val immutableSet = setOf(1, 2, 3)
val mutableSet = mutableSetOf(1, 2, 3)
mutableSet.add(4)
Collection Operations
Kotlin includes many extension functions for collections, such as filter
, map
, reduce
.
val numbers = listOf(1, 2, 3, 4, 5)
val evens = numbers.filter { it % 2 == 0 }
val squares = numbers.map { it * it }
Classes and Objects
Class Declaration
Kotlin uses the keyword class
to define classes. Primary constructors are defined on the same line.
class Person(val name: String, var age: Int)
Creating an Instance
Instances of classes are created without the new
keyword.
val person = Person("Luis", 25)
Properties and Methods
Classes can have properties and methods.
class Car(val model: String) {
var speed: Int = 0
fun accelerate() {
speed += 10
}
}
Inheritance
In Kotlin, classes are final
by default. To allow inheritance, open
is used.
open class Animal(val name: String) {
open fun sound() = "Makes a sound"
}
class Dog(name: String) : Animal(name) {
override fun sound() = "Barks"
}
Data Classes
Kotlin provides data class
to store data. These classes automatically implement toString()
, hashCode()
, and equals()
.
data class User(val name: String, val age: Int)
Null Safety
Nullable Types
In Kotlin, types are non-null by default. To allow a variable to hold null
, ?
is added to the type.
var name: String? = null
Safe Call and Not Null Assertion
The safe call (?.
) prevents NullPointerExceptions. The not-null assertion (!!
) ensures that a variable is not null but throws an exception if it is.
val length: Int? = name?.length
val forcedLength: Int = name!!.length
Advanced Object-Oriented Programming
Interfaces
Kotlin supports interfaces that can contain abstract methods and methods with implementations.
interface Flyer {
fun fly()
fun takeOff() = println("Taking off")
}
Delegation
Kotlin supports delegating interface implementation to other objects.
class Bird : Flyer by Airplane()
Advanced Features
Extensions
Kotlin allows adding new functions to existing classes without directly modifying them.
fun String.repeat(times: Int): String {
return this.repeat(times)
}
println("Hello".repeat(3)) // HelloHelloHello
Sealed Classes
Sealed classes restrict inheritance, allowing only a defined set of subclasses.
sealed class Result
class Success(val data: String) : Result()
class Error(val message: String) : Result()
Coroutines
Kotlin has native support for coroutines, making asynchronous programming easier.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World")
}
println("Hello")
}
Exception Handling
Try-Catch
Exceptions in Kotlin are handled with try-catch
blocks.
try {
val number = "abc".toInt()
} catch (e: NumberFormatException) {
println("Number format error")
} finally {
println("Completion")
}
Throw
Throw an exception explicitly.
fun checkAge(age: Int) {
if (age < 18) {
throw IllegalArgumentException("Insufficient age")
}
}
Interoperability with Java
Calling Java Code
Kotlin is fully interoperable with Java, allowing direct calls to Java libraries.
val javaList: java.util.ArrayList<String> = java.util.ArrayList()
javaList.add("Hello")