Search code examples
kotlinkotlin-null-safety

handle a object that can return null in kotlin


Android Studio 3.0

I am have java code that I am converting to Kotlin for my project.

public String getAuthUserEmail() {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String email = null;
        if (user != null) {
            email = user.getEmail();
        }
        return email;
}

I have converted it to koklin like this:

   fun getAuthUserEmail(): String? {
        val user: FirebaseUser? = FirebaseAuth.getInstance().currentUser

        return user?.email
    }

I am just wondering in my kotlin version if the user happens to be null. Should I need to have an if condition to check if the user is null?

I could have the function as a one line

   fun getAuthUserEmail(): String? {
       return FirebaseAuth.getInstance().currentUser.email?
    }

And would the calling function need to handle a null string that could be return from the function?

Many thanks for any suggestions


Solution

  • Should I need to have an if condition to check if the user is null?

    According to Firebase's doc:

    Returns the currently signed-in FirebaseUser or null if there is none.

    Use getCurrentUser() != null to check if a user is signed in.

    So, it depends on how you want to handle when there is no signed-in user.

    If you want the function to be one-lined, you can chain it like this:

    fun getAuthUserEmail(): String? {
        return FirebaseAuth.getInstance().currentUser?.email
    }
    

    It will return null if currentUser is null or currentUser?.email is null.


    Edit: If you simply want to return email if it exists. It's ok to write it in one line, since safe calls can be chained.