Kotlin Essentials with Examples:

Here’s a Kotlin cheat sheet covering some basic concepts and syntax:

  1. Basic Structure:
				
					fun main(args: Array<String>) {
    // Your code here
}
				
			
  1. Variables and Data Types:
				
					val constantVar: Int = 10 // Immutable (read-only) variable
var mutableVar: String = "Hello" // Mutable variable
				
			
  1. Nullability:
				
					val nullableVar: String? = null // Nullable variable
val nonNullableVar: Int = 42 // Non-nullable variable
				
			
  1. Conditional Expressions:
				
					val result = if (condition) {
    // Code if condition is true
} else {
    // Code if condition is false
}
				
			
  1. When Expression (similar to Java‘s switch statement):
				
					val result = when (x) {
    1 -> "One"
    2 -> "Two"
    else -> "Unknown"
}
				
			
  1. Loops:
				
					// For loop
for (i in 1..10) {
    println(i)
}

// While loop
while (condition) {
    // Code
}

// Do-while loop
do {
    // Code
} while (condition)
				
			
  1. 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
				
			
  1. Functions:
				
					fun functionName(param1: Int, param2: String): ReturnType {
    // Code
    return result
}
				
			
  1. 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"

				
			
  1. Classes and Objects:
				
					class MyClass {
    var property: String = "Value"
    fun method() {
        // Code
    }
}

val obj = MyClass()
				
			
Social Share: