我执行一个函数(listOf(matchUid, first_name, gender, matchBio, age).any { it == null }
),该函数检查传入的任何变量是否为null
:
private fun getMatchData(doc: DocumentSnapshot){
val matchUid = if (isUser1) doc.getString("user2") else doc.getString("user1")
val first_name = if (isUser1) doc.getString("user2name") else doc.getString("user1name")
val gender = if (isUser1) doc.getString("user2gender") else doc.getString("gender")
val matchBio = if (isUser1) doc.getString("user2bio") else doc.getString("user1bio")
if ( listOf(matchUid, first_name, gender, matchBio, age).any { it == null } ) return goOffline()
if (matchUid == null) return goOffline()
if (!isUser1) Group = Group().apply {
id = doc.id
user1 = matchUid
user2 = user.uid
match = User(matchUid, first_name, gender, null, true)
}
即使检查了这一点,由于空安全性,first_name
和gender
在编译器中也带有红色下划线。 matchUid
没有红线,因为我在下面的行中明确检查是否为空。
为什么我已经检查过编译器,为什么编译器仍然给出空警告?
答案 0 :(得分:2)
所以,问题在于编译器不够智能,或者...我们没有提供足够的信息。
在您的情况下,您需要确保firstName
和gender
不为空的有问题的呼叫是:
if (listOf(matchUid, firstName, gender, matchBio, age).any { it == null }) return goOffline()
如果将其更改为简单的null链,它将可以正常工作:
if (matchUid == null || firstName == null || gender == null || matchBio == null || age == null) return goOffline()
那为什么呢?编译器只是不知道listOf(vararg objects: Any?).any { it == null }
的意思是,所有这些对象都不为空。
那么,我们能做什么?
Kotlin 1.3为我们提供了编写contracts
的巨大可能性,这是编译器的提示,例如,如果f(x)
返回true
表示x
不为空。但是,不幸的是,合同不支持varargs参数(或者我还没有找到一种方法)。
因此,在您的情况下,您可以将呼叫替换为单空检查链。