🟢 शुरुआत · Lesson 06
Kotlin OOP, Null Safety और Lambdas
Classes और objects
Class एक blueprint है; object उससे बनी असली चीज़। Kotlin properties को header (primary constructor) में ही रखता है।
Kotlin
class Student(val name: String, var marks: Int) {
fun passed() = marks >= 33
fun describe() = "$name scored $marks (${if (passed()) "pass" else "fail"})"
}
fun main() {
val s = Student("Riya", 82)
println(s.describe())
s.marks = 25
println(s.describe())
}Riya scored 82 (pass)
Riya scored 25 (fail)
Data classes
Kotlin
data class Note(val id: Int, val title: String, val isDone: Boolean = false)
fun main() {
val a = Note(1, "Maths homework")
val b = a.copy(isDone = true) // copy with one change
println(a)
println(b)
println(a == Note(1, "Maths homework")) // compares values
val (id, title) = a // destructuring
println("$id → $title")
}Note(id=1, title=Maths homework, isDone=false)
Note(id=1, title=Maths homework, isDone=true)
true
1 → Maths homework
Inheritance और interfaces
Kotlin
open class Shape(val name: String) {
open fun area(): Double = 0.0
fun info() = "$name area = ${"%.2f".format(area())}"
}
class Circle(private val r: Double) : Shape("Circle") {
override fun area() = Math.PI * r * r
}
class Rect(private val w: Double, private val h: Double) : Shape("Rectangle") {
override fun area() = w * h
}
interface Clickable { fun onClick(): String }
class SaveButton : Clickable {
override fun onClick() = "Saving note…"
}
fun main() {
val shapes: List<Shape> = listOf(Circle(2.0), Rect(3.0, 4.0))
shapes.forEach { println(it.info()) }
println(SaveButton().onClick())
}Circle area = 12.57
Rectangle area = 12.00
Saving note…
object, companion object और enum
Kotlin
object AppConfig { // singleton – exactly one instance
const val BASE_URL = "https://codingeasily.in/"
var darkMode = false
}
class Counter {
companion object { // like Java "static"
const val MAX = 3
fun create() = Counter()
}
var value = 0
fun inc() { if (value < MAX) value++ }
}
enum class Priority(val label: String) { LOW("Low"), MEDIUM("Medium"), HIGH("High") }
fun main() {
println(AppConfig.BASE_URL)
val c = Counter.create()
repeat(5) { c.inc() }
println(c.value)
println(Priority.HIGH.label)
println(Priority.entries.joinToString { it.name })
}https://codingeasily.in/
3
High
LOW, MEDIUM, HIGH
Null safety
पहले सबसे आम Android crash NullPointerException था। Kotlin में normal type कभी null नहीं हो सकता; allow करने के लिए ? लगाएँ, फिर compiler आपको उसे handle करने पर मजबूर करता है।
Kotlin
fun main() {
var subject: String? = null // ? = may be null
println(subject?.length) // safe call → null, no crash
println(subject ?: "General") // Elvis: default value
subject = "Physics"
println(subject?.length)
subject?.let { println("Subject is $it") } // runs only if not null
val input = "abc"
val number = input.toIntOrNull() ?: 0
println(number)
}null
General
7
Subject is Physics
0
| Operator | मतलब |
|---|---|
a?.b | Safe call: a null नहीं तो b, नहीं तो null |
a ?: x | Elvis: a, या a null हो तो x |
a?.let { } | a null न हो तभी block चलाओ |
a!! | Force — null हुआ तो crash (बचें) |
Lambdas और collection functions
Lambda { } के अंदर लिखा छोटा function है। एक parameter का default नाम it होता है।
Kotlin
data class Note(val title: String, val priority: Int, val isDone: Boolean)
fun main() {
val notes = listOf(
Note("Maths homework", 2, false),
Note("Buy notebook", 0, true),
Note("Physics revision", 1, false)
)
val pending = notes.filter { !it.isDone }
val titles = pending.map { it.title.uppercase() }
val sorted = notes.sortedByDescending { it.priority }
println(titles)
println(sorted.first().title)
println(notes.count { it.isDone })
val onClick: (String) -> Unit = { title -> println("Clicked $title") }
onClick("Maths homework")
val note = Note("Draft", 1, false)
// scope function "with": use the object's properties directly
println(with(note) { "$title has priority $priority" })
}[MATHS HOMEWORK, PHYSICS REVISION]
Maths homework
1
Clicked Maths homework
Draft has priority 1
Android इन्हें कैसे use करता है
Kotlin – असली Android code
class MainActivity : AppCompatActivity() { // inheritance
override fun onCreate(savedInstanceState: Bundle?) { // override + nullable Bundle
super.onCreate(savedInstanceState)
binding.btnSave.setOnClickListener { save() } // lambda
val name = intent.getStringExtra("name") ?: "Guest" // Elvis
}
}
@Entity data class Note(@PrimaryKey val id: Long, val title: String) // data class
object TipsApi { const val BASE_URL = "https://codingeasily.in/" } // objectआम गलतियाँ
- जो class
openनहीं उसे extend करना → "This type is final"। - हर जगह
!!→ crashes वापस आते हैं।?.,?:,letuse करें। - Normal class के objects को
==से compare करना → references compare होते हैं; data class use करें। overridekeyword भूलना → compile error।
सारांश
- Constructor में properties वाली classes; models के लिए
data class। - Inheritance के लिए
open/override; contracts के लिए interfaces। object= singleton;companion object= static जैसे members।?,?.,?:से null safety; filter/map/sortedBy के साथ lambdas।
✅ Practice
data class Product(val name: String, val price: Int, val discount: Int?) बनाइए। 5 products की list से ₹1000 से कम वाले products के नाम और discount ?: 0 से final price print कीजिए।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
Kotlin में !! का क्या मतलब है?
यह Kotlin से कहता है "मुझे पक्का पता है यह null नहीं है"। Null हुआ तो app NullPointerException से crash होगी, इसलिए इससे बचें और ?. या ?: use करें।
Kotlin classes default रूप से final क्यों हैं?
गलती से inheritance रोकने के लिए। जब class या function को extend/override करना हो तो उस पर open लगाएँ।
Data class कब use करें?
उन classes के लिए जो मुख्य रूप से data रखती हैं, जैसे Note, Product या API response। equals, toString और copy free में मिलते हैं।
