android - 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?
)
解决方案
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.
推荐阅读
- react-native - React Native 自动 RTL 文本开关在 IOS 中不起作用,但在 android 中有效
- ruby-on-rails - Rails - 如何从 JSON Web 密钥获取公钥?
- perl - Catalyst:将 URL 与特定但可选的参数匹配
- azure - 在 Azure API 管理入站策略部分中获取路由参数
- angular - ngrx:集合中每个元素的加载状态
- java - JPA 存储库表不保存新 ID,而是覆盖或修改
- azure - Outlook.office365.com IMAP OAuth2 身份验证问题
- python - 使用 Pandas 时如何解决内存错误?
- angular - Angular 9、KeyCloak、ServiceWorker 和 Edge 浏览器
- javascript - 我怎样才能让箭头进入时钟?