How to avoid using java8 methods with Kotlin and Android


#1

If I create a brand new kotlin project using Android Studio 3.0 (jre7 kotlin).

implementation “org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version”

Then put into onCreate()

val map = mapOf(“a” to “b”)
map.getOrDefault(“a”, “z”)

Then deploy to a device with API level 21 (not supporting java8).

It results in a crash:

java.lang.NoSuchMethodError: java.util.Map.getOrDefault

How do I avoid putting broken code like this into production?

There are no warnings in Android Studio. I would have thought having a jre7 kotlin dependency would know to not attempt to call a java8 method?

I don’t really want to be writing code and having to second guess which methods will really work.


#2

These functions are added by the latest version of the Android framework. You may be able to leverage android lint to warn you, otherwise use a build sdk version that doesn’t include jdk8 support (at least when building some build, not the final product)