kotlin - 处理可以在Kotlin中返回null的对象

标签 kotlin kotlin-null-safety

Android Studio 3.0

我有要转换为项目的Kotlin的Java代码。
public String getAuthUserEmail() {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String email = null;
        if (user != null) {
            email = user.getEmail();
        }
        return email;
}

我已将其转换为koklin,如下所示:
   fun getAuthUserEmail(): String? {
        val user: FirebaseUser? = FirebaseAuth.getInstance().currentUser

        return user?.email
    }

我只是想知道在我的kotlin版本中,该用户是否恰好为空。我是否需要一个if条件来检查用户是否为空?

我可以将其作为一行
   fun getAuthUserEmail(): String? {
       return FirebaseAuth.getInstance().currentUser.email?
    }

调用函数是否需要处理可能从函数返回的空字符串?

非常感谢您的任何建议

最佳答案

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


根据Firebase的文档:

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

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


因此,这取决于没有登录用户时您要如何处理。
如果您希望函数是单行的,可以像这样链接它:
fun getAuthUserEmail(): String? {
    return FirebaseAuth.getInstance().currentUser?.email
}
如果currentUser为null或currentUser?.email为null,它将返回null。

编辑:如果您只想返回电子邮件(如果存在)。可以将其写在一行中,因为safe calls可以链接。

关于kotlin - 处理可以在Kotlin中返回null的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571981/

相关文章:

Kotlin 类型不匹配 : required Array<Int? >?但发现 Array<Int>

unit-testing - 协程测试失败, "This job has not completed yet"

javafx - 带有 TestFX 的 TornadoFX 在每个 TestCase 后关闭 View

android - IO异常 : AsyncTask Image Download Kotlin Android (Bad File Descriptor)

kotlin - 结合 null 安全性和 assertNotNull

kotlin - 从 kotlin 中的集合中过滤掉非空值

android - 无法打印整个字符串值

java - 在嵌入式 Jetty 中设置默认字符编码和内容类型

kotlin - Dart "sound null-safety"与 Kotlin 空安全有何不同?

kotlin - 在 Kotlin 中进行空检查的最佳方法?