CodexBloom - Programming Q&A Platform

NullPointerException when accessing nested properties in Kotlin data classes with nullable types

👀 Views: 69 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
kotlin null-safety data-classes Kotlin

I'm reviewing some code and Quick question that's been bugging me - I'm working on a project and hit a roadblock. I'm working with a `NullPointerException` when attempting to access properties from a nested data class in Kotlin. I've defined a data class structure where the outer class has a nullable property that contains another data class. Here's a simplified version of the code: ```kotlin data class User(val name: String, val profile: Profile?) data class Profile(val age: Int, val email: String) fun printUserEmail(user: User) { println(user.profile!!.email) // This line throws NullPointerException if profile is null } ``` When I call `printUserEmail()` with a `User` instance that has a `null` `profile`, it crashes with `kotlin.KotlinNullPointerException`. I've tried using the safe call operator `?.` instead, like this: ```kotlin fun printUserEmail(user: User) { println(user.profile?.email ?: "No email available") } ``` This seems to work fine, but I want to understand why the original approach fails without proper null checks. I also want to ensure that I'm following best practices for handling nullable types in Kotlin. Are there better patterns or practices I should be aware of to prevent these errors in my code? My development environment is Windows. How would you solve this? This is my first time working with Kotlin stable. Thanks, I really appreciate it! Any advice would be much appreciated. I'm developing on Linux with Kotlin. Is there a simpler solution I'm overlooking?