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
135: Contracts for Compiler Smart-Casting
I was working on a user profile module yesterday and ran into one of those "I know this is true, why doesn't the compiler know this is true" moments. I wanted to pull out the logic for validating if a user's bio is actually usable—meaning it's not null and not just a bunch of whitespace—into its own helper function to keep my main logic clean.
The frustration of the "invisible" null check
I started with something simple. Here is the helper function I wrote and how I tried to use it:
fun isBioUsable(bio: String?): Boolean {
return bio != null && bio.isNotBlank()
}
fun printBio(userBio: String?) {
if (isBioUsable(userBio)) {
// I know for a fact userBio is not null here... right?
println("User bio length is: ${userBio.length}")
}
}
As soon as I typed userBio.length, the IDE screamed at me. "Smart cast to 'String' is impossible, because 'userBio' is a mutable property that could be changed" (or in this case, simply that the compiler doesn't track the result of isBioUsable).
It's annoying. I've explicitly checked for null inside isBioUsable, and that function returned true, so logically, userBio cannot be null inside that if block. But the Kotlin compiler treats functions as black boxes. It sees a function that returns a Boolean, but it has no idea why it returned true or what that implies about the arguments passed into it.
Teaching the compiler a new trick
To fix this, we need to stop treating the function as a black box and instead give the compiler a "contract." This is where kotlin.contracts comes in. I'm going to rewrite the helper to tell the compiler: "If this function returns true, you can bet your life that the argument is not null."
Check out the adjustment here:
import kotlin.contracts.*
fun isBioUsable(bio: String?): Boolean {
contract {
returns(true) implies (bio != null)
}
return bio != null && bio.isNotBlank()
}
fun printBio(userBio: String?) {
if (isBioUsable(userBio)) {
// Now the compiler is happy!
println("User bio length is: ${userBio.length}")
}
}
The contract block is the magic. By adding returns(true) implies (bio != null), I'm explicitly linking the return value of the function to the state of the variable. Now, when the compiler sees if (isBioUsable(userBio)), it doesn't just see a boolean; it sees a guarantee that userBio is now a non-nullable String for the remainder of that scope.
The fine print
Now, before you go adding contracts to every helper function in your project, there are a few things I learned the hard way. First, the contract block must be the very first statement in the function body. If you put a print statement or a variable assignment above it, the compiler will throw a fit.
Second, contracts are currently marked as an experimental feature. Depending on your Kotlin version, you'll likely need to add @OptIn(ExperimentalContracts::class) to your function or your project configuration. It's a bit of a hurdle, but for complex validation logic, it's a lifesaver. It saves you from having to use the non-null assertion operator (!!), which, as you know, is basically a "crash here if I'm wrong" button.
I usually only reach for contracts when I have a validation utility that is used in dozens of places. For a one-off check, a simple if (bio != null) is fine, but once that logic gets reused, contracts keep the call-site clean without sacrificing type safety.
📋 Practical Task
Fixing the Administrative Permission Guard
You are building a permission system for an admin dashboard. You have a helper function called hasAdminPrivileges that checks if a User object is not null and has the "ADMIN" role. However, the compiler is refusing to smart-cast the User object to non-nullable in the main logic, forcing the developer to use !!.
Your Task: Modify the hasAdminPrivileges function to include a contract so that the compiler knows that if the function returns true, the user parameter is definitely not null.
import kotlin.contracts.*
data class User(val name: String, val role: String)
// TODO: Add a contract here to enable smart-casting
fun hasAdminPrivileges(user: User?): Boolean {
return user != null && user.role == "ADMIN"
}
fun accessSecurePanel(currentUser: User?) {
if (hasAdminPrivileges(currentUser)) {
// Currently, this line causes a compilation error:
// "Smart cast to 'User' is impossible"
println("Welcome to the secure panel, ${currentUser.name}!")
} else {
println("Access Denied.")
}
}
fun main() {
val admin = User("Alice", "ADMIN")
val guest = User("Bob", "GUEST")
accessSecurePanel(admin)
accessSecurePanel(guest)
accessSecurePanel(null)
}There are no comments for now.