Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lint considers Kotlin MutableMap.forEach() as java.util.Map.forEach()

I am using Kotlin's MutableMap in my Android project. And trying to do some action per item. So here is my code.

private val uris: MutableMap<String, Uri> = mutableMapOf()
// ... Fill the items here ...
uris.forEach {
    val ref = FirebaseFirestore.getInstanse().reference
    uploadFile(ref, it.value)
}

Everything just works fine at runtime, but my CI build fails with below lint error:

MyActivity.kt:142: Error: Call requires API level 24 (current min is 16): java.util.Map#forEach [NewApi]
              uris.forEach {
                   ~~~~~~~

I know we can't use JDK-8's Map for Android projects until the min sdk is 24. But why lint is considering it as JDK-8's Map?

For further information I tried getting the Java code from Kotlin Bytecode option in AS and found that forEach is replaced with while loop and iterator as expected.

So what could be reason and how to solve this? Any lead will be appreciated.

like image 337
Chandra Sekhar Avatar asked Jan 25 '18 07:01

Chandra Sekhar


2 Answers

There are two overloaded foreachs on Map:

Kotlin one:

uris.forEach { (key, value) -> // Do some Action }

Java8 one:

uris.forEach { key, value -> // Do some Action }

Confusing, isn't it?

like image 91
voddan Avatar answered Nov 17 '22 23:11

voddan


I think this is an import problem. Maybe you have used JDK 8's Map.forEach.

You have to use kotlin.collections.MutableMap.forEach

You can also check this blog:

http://blog.danlew.net/2017/03/16/kotlin-puzzler-whose-line-is-it-anyways/

like image 2
Avijit Karmakar Avatar answered Nov 17 '22 22:11

Avijit Karmakar