34

I just noticed this lint error:

Call requires API Level 24 (current min is 19) java.util.map#foreach

when I use the extension function forEach on a MutableMap in Kotlin. This didn't happen when I wrote the line, but its there now. And I'm not seeing this error on my other machine.

4

4 回答 4

76

您使用的不是kotlin.collections.MutableMap.forEach.

您使用的似乎是Map.forEach在 Java 8 中。

参考这篇文章: http ://blog.danlew.net/2017/03/16/kotlin-puzzler-whose-line-is-it-anyways/

这似乎是一个常见的错误。

Java 8 从 Android API 级别 24 得到很好的支持。

简而言之,不要使用forEachlike map.forEach { t, u -> Log.i("tag", t + u) }(这是使用Java 8 API,不适用于Android API level <= 23)。
像使用它map.forEach { (t, u) -> Log.i("tag", t + u) }(这是使用 Kotlin API)。
(不是两个参数。只有一个参数是一对。)

于 2017-06-26T01:56:33.930 回答
6

即使我正在使用我需要使用的列表中也会发生这种情况:

list.iterator().forEach {}

关键是iterator()在 forEach 之前使用。

于 2021-05-28T11:25:40.677 回答
0

遇到此问题是因为提供的依赖项映射是 Java 8 映射,因此forEach无论我如何在 lambda 签名 ( one, two ->vs (one, two) ->) 中对参数进行分组,它都被视为 Java 8 版本。我能找到的最佳解决方案是使用带有别名 ( import kotlin.collections.forEach as kForEach) 的显式导入。别名使优化导入不会删除显式导入。

于 2021-08-23T18:46:11.200 回答
-4

Java 8 支持 Map.forEach,Android 支持从 API 24 开始

于 2017-06-26T05:38:23.910 回答