Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
16: Smart Casts
Imagine you're working in a warehouse and a mystery box lands on your conveyor belt. You don't know what's inside, but you see a label that says "Electronics." Once you read that label, you don't need to keep guessing. You don't have to ask, "Is this a gadget?" every single time you reach in to grab a cable or a screen. You've already verified it's an electronic device, so for the rest of the time you're handling that box, you treat it as one.
In Kotlin, that's exactly how smart casts work. Instead of you manually forcing the compiler to treat a variable as a specific type (which is what "casting" usually means in other languages), Kotlin watches your logic. If you check if a variable is a certain type, Kotlin says, "Got it. I'll remember that for you," and automatically treats it as that type within that scope.
The 'Is' Operator as a Gatekeeper
In Java, you're probably used to a clumsy two-step process: first you check if an object is a certain type, and then you explicitly cast it using parentheses. It's redundant and noisy. Kotlin kills that pattern with the is operator.
Let's look at a real scenario. Imagine we're building a payment system where we have different payment methods, but some of them have specific details we need to access.
sealed class PaymentMethod {
class CreditCard(val cardNumber: String, val expiry: String) : PaymentMethod()
class PayPal(val email: String) : PaymentMethod()
object Cash : PaymentMethod()
}
fun processPayment(method: PaymentMethod) {
if (method is PaymentMethod.CreditCard) {
// Inside this block, 'method' is automatically cast to CreditCard
println("Charging card: ${method.cardNumber}")
} else if (method is PaymentMethod.PayPal) {
// Now it's automatically treated as PayPal
println("Redirecting to PayPal email: ${method.email}")
} else {
println("Handling cash payment.")
}
}
Notice that inside the first if block, I didn't have to write something like (method as CreditCard).cardNumber. Because I used is, Kotlin "smartly" cast the method variable for me. It's cleaner, and more importantly, it's safer because the cast only happens after the check succeeds.
When the Magic Fails: The Var Problem
I should give you a heads-up: smart casts aren't invincible. I've seen plenty of developers get frustrated when a smart cast suddenly disappears. The culprit is almost always a var (a mutable variable).
Think back to the warehouse analogy. If you verify a box is "Electronics," but then someone else in the warehouse might swap the contents of that box while you're not looking, you can't trust your previous check. The compiler thinks the same way. If a variable is mutable and could potentially be changed by another thread or a different part of your code between the check and the usage, Kotlin won't perform the smart cast.
Here is a quick example of what won't work:
var currentUser: Any = "John Doe"
if (currentUser is String) {
// This works fine here...
println(currentUser.length)
}
// But if currentUser is a class-level property (a var),
// Kotlin might complain that it can't smart cast it because
// it could have changed between the 'is' check and the usage.
The fix? Use val whenever possible. If you must use a var, you can capture it in a local val first, or use the let function to create a temporary, immutable reference.
The Logical NOT Shortcut
One of my favorite little shortcuts in Kotlin is the "inverted" smart cast. If you check that something is not a certain type, Kotlin is smart enough to rule that type out for the rest of the block.
fun handleInput(input: Any) {
if (input !is String) return // Exit early if it's not a string
// From here on down, Kotlin knows 'input' MUST be a String
println("The input length is ${input.length}")
}
This is a great way to flatten your code and avoid deeply nested if statements. You handle the "wrong" types first and get them out of the way, leaving the rest of your function clean and typed.
📋 Practical Task
Build a Media File Processor
You are building a system that processes different types of media files. You have a base class MediaFile and two subclasses: AudioFile (which has a bitrate property) and VideoFile (which has a resolution property).
Your Task:
- Create the
MediaFilehierarchy. - Write a function called
printFileDetails(file: MediaFile). - Inside the function, use smart casts to:
- Print the bitrate if the file is an
AudioFile. - Print the resolution if the file is a
VideoFile. - Print "Generic media file" if it is neither.
- Print the bitrate if the file is an
- Test your function by passing it both an
AudioFileand aVideoFileinstance.
There are no comments for now.