Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio Kotlin type mismatch for platform types

Tags:

android

kotlin

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?)

like image 380
rosghub Avatar asked Dec 18 '18 19:12

rosghub


1 Answers

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.

like image 172
tynn Avatar answered Nov 19 '22 16:11

tynn