首页 > 解决方案 > Android Studio Kotlin type mismatch for platform types

问题描述

In all of my kotlin projects, I have found new warnings involving what use to be platform types. For example

val s: String = sharedPrefs.getString("key", "defaultValue")

produces a warning

Type mismatch: inferred type is String? but String was expected

It compiles fine though so it seems to be unrelated to kotlins enforcing nullable type. But this warning seems to have popped up in the recent weeks which may be related to a change in android studio or the kotlin plugin.

In this specific case, why doesn't the inferred type match what I provided in the 2nd argument (a String not a String?)

标签: androidkotlin

解决方案


Looking at the code of SharedPreferences, it's defined as

@Nullable
String getString(String key, @Nullable String defValue);

Having a look at it within Android Studio, the code implies

@Contract(value="_,!null->!null")

But this is not defined within the source itself and not considered by Android Studio. When you have a closer look at the warning itself, you'll find it's the Kotlin NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS JVM errors diagnostic.

Anyhow the @Nullable annotation is just a suggestion, and the explicit declaration takes precedence.


推荐阅读