Android Studio plugin unable to infer null safety


#1
val profilesModel: Map<Profile, String>
var Config.custom: Profile?

val profiles: List<Profile>
    get() = Config.custom.let {
        // if 'it' is null, the else branch will never be executed, so '!!' should be inferred
        if (it?.isSaved ?: true) profilesModel.keys else profilesModel.keys.plus(it!!)
    }.sorted() // If '!!' is ommitted, gives a type inference error: receiver type is Set<Profile?>

Or am I missing something and the compiler is just smarter than I am?


#2

It’s more or less the same as reported here: https://youtrack.jetbrains.com/issue/KT-17302 or here: https://youtrack.jetbrains.com/issue/KT-4565. In general, there are some complex cases when compiler is unable to infer nullability precisely enough to do smart cast.


#3

I can offer you a good workaround: replace your ?: true with != false (BTW there is an IDE inspection suggesting this change because it’s a recommended style). After it you will get your smart cast.