kotlin中使用by lazy命名引起的bug

293 阅读1分钟

1.问题描述

在编译下面代码时提示Platform declaration clash: The following declarations have the same JVM signature (getApp()Landroid/app/Application;):异常。

class App : Application() {

    val app by lazy { getApp() }
    override fun onCreate() {
        super.onCreate()
    }

    fun getApp(): Application {
        return this
    }
}

2.原因分析

通过tools工具发现kotlin编译后的字节码转成java如下,居然出现了两个getApp()方法。可以推断其中一个getApp是我们定义的,而另一个getApp应该是定义的变量val app 生成的,所以出现了两个getApp导致的冲突。

public final class App extends Application {
   @NotNull
   private final Lazy app$delegate = LazyKt.lazy((Function0)(new Function0() {
      // $FF: synthetic method
      // $FF: bridge method
      public Object invoke() {
         return this.invoke();
      }

      @NotNull
      public final String invoke() {
         return App.this.getApp();
      }
   }));

   @NotNull
   public final Application getApp() {
      // $FF: Couldn't be decompiled
   }
   //...

   @NotNull
   public final Application getApp() {
      // $FF: Couldn't be decompiled
   }
}

3.解决办法

通过修改名字,避免冲突。