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
61: Building APIs with Spring Boot and Kotlin
I've noticed a recurring pattern when developers first jump from Java to Kotlin within the Spring ecosystem. They tend to carry over the "Java baggage"—specifically, the habit of using field injection. You'll see codebases littered with @Autowired annotations on lateinit var properties. They think that because Spring is a Java framework, they have to play by those rules to make the dependency injection engine happy.
The "Autowired" Crutch
// This is how many people start. It's technically "correct" in that it works,
// but it's a missed opportunity for safety.
@RestController
class BookController {
@Autowired
lateinit var bookService: BookService
@GetMapping("/books")
fun getBooks() = bookService.findAll()
}
The problem here is that you're telling Kotlin, "Trust me, this variable will be initialized later." You've introduced mutability (var) and a potential UninitializedPropertyAccessException if you ever try to instantiate this class in a unit test without starting the entire Spring context. It's clunky, and frankly, it ignores why we chose Kotlin in the first place.
Constructor Injection and the Power of val
In modern Spring, you don't need @Autowired on your fields. Spring is smart enough to see a single constructor and inject the dependencies automatically. By moving your dependencies into the primary constructor, you can use val. This makes your controller immutable and guarantees that the class is never in an invalid state.
// This is the Kotlin way. Clean, immutable, and test-friendly.
@RestController
class BookController(private val bookService: BookService) {
@GetMapping("/books")
fun getBooks(): List<BookResponse> = bookService.findAll()
}
See the difference? No lateinit, no mutable state. If you want to test this controller, you can just pass a mocked BookService directly into the constructor—no reflection or Spring Runner required. I always tell my juniors: if you're typing @Autowired on a field in 2024, you're probably doing it wrong.
Leveraging Data Classes for API Contracts
One of the most satisfying parts of using Kotlin with Spring is how we handle Data Transfer Objects (DTOs). In Java, you'd have a class with a private constructor, getters, setters, and a 50-line equals() and hashCode() method. In Kotlin, we use data classes. They are perfect for defining the shape of your JSON requests and responses.
// A concise contract for creating a new book data class CreateBookRequest( val title: String, val author: String, val isbn: String, val pageCount: Int? = null // Optional field ) @PostMapping("/books") fun createBook(@RequestBody request: CreateBookRequest): ResponseEntity<BookResponse> { val book = bookService.save(request) return ResponseEntity.ok(book) }Because these are data classes, Spring's Jackson integration handles them flawlessly. You get the benefit of strict typing and named arguments without the boilerplate noise. Just be careful not to use your database entities as your API responses; always map your internal models to a DTO to avoid accidentally leaking sensitive database columns to the public internet.
Handling Nullability in Request Params
Spring's
@RequestParamand@PathVariableplay very nicely with Kotlin's null safety. If you define a parameter as a non-nullableString, Spring will automatically throw an error if that parameter is missing. If you want it to be optional, simply make it nullable.@GetMapping("/books/search") fun searchBooks( @RequestParam title: String, // Required: 400 Bad Request if missing @RequestParam genre: String? = "Fiction" // Optional: Defaults to "Fiction" ): List<BookResponse> { return bookService.search(title, genre) }This shifts the validation logic from your method body into the type system itself. You aren't writing
if (genre == null)blocks anymore; the language and the framework are handling the contract for you.
📋 Practical Task
Build a "Task Management API" Endpoint
Your goal is to implement a small part of a Task Management system. You need to create a REST controller that allows a user to mark a task as completed.
Requirements:
- Create a data class
TaskUpdateResponsecontaining ataskId: UUID,status: String, andupdatedAt: LocalDateTime. - Create a
TaskControllerthat uses constructor injection to bring in a (mocked)TaskService. - Implement a
PATCHendpoint at/tasks/{id}/complete. - The endpoint should take a
UUIDfrom the path and call a method on the service calledmarkAsComplete(id: UUID). - Return the
TaskUpdateResponsewith a200 OKstatus.
Constraint: Do not use @Autowired on any fields. Ensure all dependencies are immutable (val) and defined in the primary constructor.
There are no comments for now.