Kotlin Essentials with Examples:
Here’s a Kotlin cheat sheet covering some basic concepts and syntax:
- Basic Structure:
fun main(args: Array) {
// Your code here
}
- Variables and Data Types:
val constantVar: Int = 10 // Immutable (read-only) variable
var mutableVar: String = "Hello" // Mutable variable
- Nullability:
val nullableVar: String? = null // Nullable variable
val nonNullableVar: Int = 42 // Non-nullable variable
- Conditional Expressions:
val result = if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
- When Expression (similar to Java‘s switch statement):
val result = when (x) {
1 -> "One"
2 -> "Two"
else -> "Unknown"
}
- Loops:
// For loop
for (i in 1..10) {
println(i)
}
// While loop
while (condition) {
// Code
}
// Do-while loop
do {
// Code
} while (condition)
- Ranges:
for (i in 1..5) print(i) // Prints 1 2 3 4 5
for (i in 5 downTo 1) print(i) // Prints 5 4 3 2 1
for (i in 1..10 step 2) print(i) // Prints 1 3 5 7 9
- Functions:
fun functionName(param1: Int, param2: String): ReturnType {
// Code
return result
}
- Default and Named Arguments:
fun greet(name: String, age: Int = 0) {
println("Hello, $name. Age: $age")
}
greet("John") // "Hello, John. Age: 0"
greet("Jane", 25) // "Hello, Jane. Age: 25"
greet(age = 30, name = "Sam") // "Hello, Sam. Age: 30"
- Classes and Objects:
class MyClass {
var property: String = "Value"
fun method() {
// Code
}
}
val obj = MyClass()