Kotlin is a modern programming language that is concise, expressive, and interoperable with Java. Here’s a Kotlin cheat sheet covering some basic syntax and common features:
Hello World
Hello World:
fun main() {
println("Hello, World!")
}
Variables and Data Types
Variable Declaration:
val age: Int = 25
var name: String = "John"
Type Inference:
val pi = 3.14 // Type inferred as Double
Nullable Types:
var nullableName: String? = null
Functions
Function Definition:
fun add(x: Int, y: Int): Int {
return x + y
}
Single-Expression Function:
fun multiply(x: Int, y: Int) = x * y
Control Flow
If Expression:
val result = if (x > y) "x is greater" else "y is greater"
When Expression:
when (day) {
1 -> "Monday"
2 -> "Tuesday"
else -> "Other day"
}
For Loop:
for (i in 1..5) {
println(i)
}
Collections
List:
val numbers = listOf(1, 2, 3, 4, 5)
Mutable List:
val mutableNumbers = mutableListOf(1, 2, 3, 4, 5)
Map:
val user = mapOf("name" to "John", "age" to 25)
Here is a dedicated Kotlin Collections Cheat Sheet.
Classes and Objects
Class Declaration:
class Person(val name: String, val age: Int)
Object Declaration:
object MySingleton {
// Singleton object
}
Extension Functions:
fun String.addExclamation(): String {
return "$this!"
}
val greeting = "Hello".addExclamation()
Null Safety
Safe Call Operator:
val length: Int? = name?.length
Elvis Operator:
val length = name?.length ?: 0
Coroutines
Simple Coroutine:
suspend fun fetchData() {
// Coroutine logic
}
Launch Coroutine:
GlobalScope.launch {
fetchData()
}
Here is a dedicated Kotlin Coroutines Cheat Sheet.
Android Development (Sample)
Android TextView Initialization:
val textView = findViewById<TextView>(R.id.textView)
textView.text = "Hello, Kotlin!"
Notes
- Kotlin is interoperable with Java, making it suitable for Android development.
- It introduces features like null safety, extension functions, and coroutines.
This Kotlin cheat sheet covers some basic syntax and features. Kotlin has a rich set of features, so refer to the official Kotlin documentation for more in-depth learning.