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
249: Input Validation Patterns in Kotlin
I once worked on a project where we let users set their own custom handles for their profiles. It seemed simple enough: just a string field in the database. One afternoon, our URL generator started throwing 500 errors for a handful of users. It turned out one clever user had set their handle to a single whitespace character. Our database accepted it, our basic "is not null" check passed, but the URL builder crashed because it tried to trim the handle into non-existence before appending it to the domain. It was a classic case of "shallow validation"—checking that the data exists, but not that it actually makes sense for the business logic.
Fail-Fast with Require and Check
In Kotlin, the most immediate way to stop "garbage in" from polluting your system is by using the require and check standard library functions. I see a lot of developers writing verbose if (x == null) throw IllegalArgumentException(...) blocks, but that's just noise. You can condense that into a single, readable line.
Use require() when you are validating arguments passed into a function. If the condition is false, it throws an IllegalArgumentException. It's the "you gave me bad data" signal. On the other hand, use check() to verify the internal state of your object. If check() fails, it throws an IllegalStateException, which effectively says, "the data might be fine, but the system is in a state where this operation is impossible."
fun updateUserAge(age: Int) {
// Fail fast: don't even let the code proceed if the age is impossible
require(age in 0..120) { "Age must be between 0 and 120, but was $age" }
// Imagine we have a state check to ensure the account is active
check(this.isActive) { "Cannot update age for an inactive account" }
this.age = age
}
The trailing lambda in these functions is where you put your error message. It's lazy, meaning the string is only constructed if the validation actually fails, which is a nice little performance win.
Turning Validation into Types
While require is great, it's still reactive—you're catching the error after the function is called. If you're passing a "validated" email string through five different service layers, you have to trust that every single layer remembers to call require(). I've found that the most robust way to handle this is a pattern often called "Parse, don't validate."
Instead of passing around a String and hoping it's a valid email, create a specific type for it. Kotlin's value classes are perfect for this because they give you type safety without the memory overhead of a full wrapper object. By making the constructor private and providing a factory method, you guarantee that if an instance of that class exists, it must be valid.
@JvmInline
value class Email private constructor(val value: String) {
companion object {
fun create(input: String): Email {
require(input.contains("@") && input.contains(".")) {
"Invalid email format: $input"
}
return Email(input)
}
}
}
// Now, your business logic doesn't need to validate the email again
fun sendWelcomeEmail(email: Email) {
// No 'require' needed here; the type system guarantees validity
println("Sending email to ${email.value}")
}
This shifts the burden of validation to the very edge of your application—the API controller or the UI layer. Once the data enters your core logic as an Email type, you can stop worrying about it. It’s a bit more boilerplate upfront, but it saves you from those "single whitespace" bugs that keep you up until 2 AM.
📋 Practical Task
Implementing a Validated Order System
You are building a checkout system for an e-commerce app. You need to ensure that orders cannot be created with invalid data. Your task is to implement the following validation logic:
- Create a
value class OrderId. Its constructor should be private. Provide acreatefactory method that ensures the ID is exactly 8 characters long and alphanumeric. - Create an
Orderdata class that takes anOrderIdand aquantity(Int). - Inside the
Orderinitblock, userequireto ensure that thequantityis greater than 0 and less than or equal to 100. - Write a small
mainfunction that attempts to create a valid order and an invalid order (e.g., with a quantity of -5 or an OrderId of "123"), and wrap the invalid attempt in atry-catchblock to print the error message.
There are no comments for now.