Kotlin is a modern, concise, and safe programming language developed by JetBrains. It’s officially supported by Google for Android development and can also be used for web, desktop, and backend apps.
Why Learn Kotlin?
- Concise → Less boilerplate than Java.
- Safe → Built-in null safety prevents many errors.
- Interoperable → Works with existing Java code.
- Versatile → Use it for Android, web, and server apps.
Hello World
fun main() {
println("Hello, Kotlin!")
}
Variables
val
→ Immutable (like constants).var
→ Mutable (can change).
val name = "Alice" // Cannot be changed
var age = 25 // Can be changed
Data Types
Kotlin is strongly typed but can infer types automatically.
- String →
"Hello"
- Int →
42
- Double →
3.14
- Boolean →
true
- List →
listOf("a", "b")
- MutableList →
mutableListOf(1, 2, 3)
Functions
fun greet(name: String): String {
return "Hello, $name!"
}
fun main() {
println(greet("Alice"))
}
Conditionals
val age = 18
if (age >= 18) {
println("Adult")
} else {
println("Minor")
}
When Expression
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Another day")
}
Loops
for (i in 1..5) {
println(i)
}
var x = 0
while (x < 3) {
println(x)
x++
}
Classes and Objects
class Person(val name: String, var age: Int) {
fun greet() {
println("Hi, my name is $name and I'm $age years old.")
}
}
fun main() {
val p = Person("Alice", 25)
p.greet()
}
Null Safety
Kotlin prevents null pointer errors by default.
var name: String? = null // Nullable type
println(name?.length) // Safe call (prints null)
Collections
val numbers = listOf(1, 2, 3)
for (n in numbers) {
println(n)
}
val mutable = mutableListOf(10, 20)
mutable.add(30)
Mini Project: Simple Calculator
fun add(a: Int, b: Int) = a + b
fun subtract(a: Int, b: Int) = a - b
fun main() {
println("Sum: ${add(5, 3)}")
println("Difference: ${subtract(10, 4)}")
}
Best Practices
- Prefer
val
unless a variable must change. - Use string templates (
"Hello $name"
) instead of concatenation. - Take advantage of Kotlin’s null safety.
- Write small, reusable functions.
Next Steps
- Android Development → Use Kotlin in Android Studio.
- Kotlin Coroutines → Learn async programming.
- Backend → Explore Ktor or Spring Boot with Kotlin.
Conclusion
Kotlin is a modern, safe, and fun programming language that simplifies development. It’s especially powerful for Android apps, but you can use it almost anywhere.
Start small, practice daily, and build amazing apps with Kotlin 🚀🔥
No comments:
Post a Comment