Search code examples
kotlinnull-check

check if null and do something


I'm new to Kotlin and I'm trying to figure out how to do something if a variable is null. This is what I'm trying to do

private var loggedInUser: User? = null

fun createActivity(activity: Activity) {
    loggedInUser?.activities?.put(activity.id, activity)
    //set loggedInUser.activities = hashMapOf() if null
}

Here's the User class

data class User(
        val firstname: String = "",
        val lastname: String = "",
        val email: String = "",
        val password: String = "",
        val id: String = UUID.randomUUID().toString(),
        val activities: MutableMap<String, Activity> = hashMapOf())

Solution

  • From your definition of the User class, if a value for the activities parameter isn't provided, it will use the default. Since hashMapOf() will never return null, you don't have to worry about that. In addition, activities is a val and not a nullable type, so if you have a non-null User, you have a non-null activities.

    If you're looking to set some value if a result is null, check out the Elvis Operator:

    data class User(val name: String, val friend: User? = null)
    fun main() {
        val x: User? = User("X")
        val y: User? = User("Y", x)
        val friendOfFriend = y?.friend?.friend?.name ?: "No friend"
        println(friendOfFriend) // Outputs "No friend" because x.friend was null
    }
    

    If any value is null along that call chain, it uses the value provided after the ?:, otherwise it returns the value given on the left hand side.

    Of course, that's just the most idiomatic way. You could also do:

    if (activities == null) {
        // something
    }
    

    Or any other traditional null checks.