Kotlin & Proguard & 嵌套 lambda 报错

Kotlin version: 1.2.71;

晚点试一下升级 kotlin 版本;

今天遇到的问题,也可以参考 Kotlin nested lambdas are stripped

  • 嵌套的 lambda 导致的混淆报错;
class Error {
  fun run() {
    with(Unit) {
      runLambda {
        runLambda {
          println("Hello, World!")
        }
      }
    }
  }
  private fun runLambda(lambda: () -> Unit) = lambda()
}
  • 错误信息:
Warning: xxx.Error$run$1$1$1: can't find referenced class xxx.Error$run$1$1
Warning: xxx.Error$run$1$1$1: can't find referenced class xxx.Error$run$1$1
  • 有人回复:

Thanks for your report. The class Error$run$1$1$1 in the compiled Kotlin code references a class Error$run$1$1 which is not present. The reference is from a constant that is not actually used in the code, so technically the compiled code is valid. However, ProGuard tries to resolve all references before finding out that the constant is not used (and removing it). Hopefully the Kotlin compiler will clean up its generated code somewhat in the future. For the time being, you can work around it by letting ProGuard accept the missing reference:
-dontwarn Error$run$1$1
You can use wildcards if you have many such cases.
It's not necessary to explicitly preserve the Jetbrains annotations or Kotlin runtime in your configuration.

  • 最简单的方法如上诉使用 -dontwarn 解决

  • 也可以选择不写嵌套 lambda:

class Error {
    fun run() {
        with(Unit) {
            runLambda {
                runLambda(object: (() -> Unit) {
                    override fun invoke() {
                        println("Hello, World!")
                    }
                })
            }
        }
    }
    private fun runLambda(lambda: () -> Unit) = lambda()
}

推荐阅读更多精彩内容