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
147: Definitely Non-Nullable Types
I've seen this a dozen times in code reviews. A developer is fighting the compiler, tired of wrapping everything in ?.let { ... } or writing if (x != null) blocks for the fifth time in one function. To make the red squiggly lines go away, they use the "double bang" operator: !!.
It feels like a shortcut. You're essentially telling Kotlin, "I know more than you do. I guarantee this value is not null, so just treat it as a non-nullable type and move on." The problem is that the compiler believes you, but the runtime doesn't care about your promises. If you're wrong, your app crashes instantly.
When Assumptions Lead to NullPointerExceptions
Take a look at this snippet. Imagine we're building a simple user session manager. We have a currentUserId that is nullable because the user might not be logged in yet.
class SessionManager {
var currentUserId: String? = null
fun logOut() {
currentUserId = null
}
fun fetchUserData() {
// We're calling this from a screen that requires login,
// so we "know" the ID must be there.
val id = currentUserId!!
println("Fetching data for user: $id")
}
}
fun main() {
val session = SessionManager()
// Oops, someone called fetchUserData before the login process finished
// or after logOut() was triggered by a background timeout.
session.fetchUserData()
}
If you run this, you'll get a NullPointerException (NPE). The !! operator converted String? into a "definitely non-nullable" String. But since currentUserId was actually null, Kotlin had no choice but to throw an exception. You've essentially reintroduced the exact problem Kotlin was designed to solve.
Handling the "Impossible" Null Safely
The fix isn't just to stop using !!—though that's a good rule of thumb—but to replace the assumption with a strategy. In the case above, the assumption was "this function is only called when logged in." If that assumption is actually a requirement for the function to work, you should make that requirement explicit.
Instead of forcing the type with !!, use a guard clause. This allows you to handle the "impossible" state gracefully rather than letting the app vanish into a crash report.
class SessionManager {
var currentUserId: String? = null
fun logOut() {
currentUserId = null
}
fun fetchUserData() {
// Use a guard clause to exit early if the assumption is wrong
val id = currentUserId ?: return println("Error: No active session found.")
// Now, 'id' is automatically smart-cast to a non-nullable String
println("Fetching data for user: $id")
}
}
By using the Elvis operator ?:, we've handled the null case. If currentUserId is null, the function returns early. If it's not null, id becomes a definitely non-nullable String for the rest of the function. No crashes, no guessing, and the compiler is happy.
I'll be honest: there are very rare cases where !! is acceptable—usually in unit tests where you've manually set up the state and a null value would indicate a fundamental failure of the test setup. But in production code? Treat !! as a code smell. If you feel the urge to use it, ask yourself: "What happens to the user if I'm wrong about this being non-null?"
📋 Practical Task
Fixing the Fragile Payment Processor
You are working on a payment module where the currencyCode is fetched from a remote configuration file. A previous developer used the !! operator, assuming the config file would always be loaded before any payment is processed. However, during slow network starts, the app is crashing.
Your Task: Rewrite the processPayment function to remove the !! operator. Instead, use a guard clause or the Elvis operator to provide a default currency of "USD" if the currencyCode is null, ensuring the function never throws a NullPointerException.
class PaymentProcessor {
var currencyCode: String? = null // Loaded asynchronously from server
fun processPayment(amount: Double) {
// BUG: This line crashes if currencyCode hasn't loaded yet
val currency = currencyCode!!
println("Processing payment of $amount in $currency")
}
}
fun main() {
val processor = PaymentProcessor()
// Simulate calling the method before the config has loaded
processor.processPayment(99.99)
}There are no comments for now.