可空WeakHashMap迭代期间的Kotlin空检查

时间:2019-12-14 00:25:41

标签: kotlin

// I know activity is not ideal here due to lack of equality guaranty; please ignore this part
private val mActivities: WeakHashMap<Activity, Int> = WeakHashMap()
....
mActivities.put(null, null)
mActivities.filter { (backStackEntry: Activity?) ->
    // Issue: this does not show any errors but fails at runtime
    Logger.warn("$TAG - Activity ${backStackEntry.localClassName}")
    val entry: Activity? = backStackEntry
    // Works as expected: this does show the error as expected
    Logger.warn("$TAG - Activity ${entry.localClassName}")
}

当我尝试遍历可能包含空值的WeakHashMap时,Kotlin空安全检查不起作用。上面列出的示例。关于为什么发生这种情况的任何想法将不胜感激。谢谢!

说明 ${backStackEntry?.localClassName}有效,但是我担心的是为什么Android Studio或构建逻辑未显示${backStackEntry.localClassName}的静态检查错误或编译错误。但是使用${entry.localClassName},Android Studio会将其标记为错误。

1 个答案:

答案 0 :(得分:1)

WeakHashMap<Activity, Int>类型不提供有关其内容为空性的信息。

请考虑将private val mActivities: WeakHashMap<Activity, Int> = WeakHashMap()替换为private val mActivities: MutableMap<Activity?, Int?> = WeakHashMap()

由于您明确指定了backStackEntry的可空性,并且编译器仍未将backStackEntry的取消引用标记为错误,因此它一定是错误,因此应在youtrack.jetbrains.com/issues/KT上进行报告。 / p>