3

How to make Kotlin give API level errors at time of coding, instead of at runtime.

App Gradle file:

minSdkVersion 19
targetSdkVersion 26

Kotlin Code:

//initialisation
var data = getSomedata() //the returned type is Map<String, String>
data.getOrDefault("SomeKey","DefaultValue")

Issue:

Code compiles fine and also able to create signed APK. But when the APK is executed on devices with API 22(Android 5) following error is thrown.

Fatal Exception: java.lang.NoSuchMethodError

Expected beheviour:

If I call the function in java file, lint checking will give following error even before compiling.

Call requires API level 24 (current min is 19): java.util.Map#getOrDefault

CHECKED DUPLICATE

Already checked this question. It is providing reason for the behavior which i have already derived. I need the resolution or work around. As of now I am not sure which all methods would not work at runtime, and users would be reporting those errors which IDE or compiler should have reported.

Sachin Chavan
  • 5,578
  • 5
  • 49
  • 75

1 Answers1

3

Quite likely this will have to be done by Android Studio/Kotlin team.

Method kotlin.Map.getOrDefault() in theory is valid on any Android API, however its internal implementation (delegating call to java.util.HashMap.getOrDefault()) is valid only on JDK 1.8+.

Moreover method kotlin.Map.getOrDefault() in its docs is marked as @since JDK 1.8. I suppose we need to wait some time for IDE team to implement a warning for methods marked in docs as @since XXX

You can also upvote or comment issues on Kotlin's YouTrack

https://youtrack.jetbrains.com/issue/KT-20358

https://youtrack.jetbrains.com/issue/KT-21503

rafal
  • 3,120
  • 1
  • 17
  • 12