Kotlin SAM Runtime Error: NoSuchMethodError: No static method

Today I came across a very strange error during the development of kotlin / android, which includes SAM conversions and a subclass.

Here is a minimal example of pure java + kotlin. Here are two java classes:

public class A { public interface I { public void f(); } public I i; } public class B extends A {} 

And here is the main function of kotlin:

 fun main(args: Array<String>) { A().i = BI {} } 

This code compiles fine, but at runtime I get the following error:

 Exception in thread "main" java.lang.NoSuchMethodError: BI(Lkotlin/jvm/functions/Function0;)LA$I; at MainKt.main(Main.kt:2) 

Now this is already bad - if such code does not work (it never guesses), the compiler should cause an error. But at least it can be said that it is a bad idea to refer to interface I via subclass B instead of where A defined (i.e. AI ).

This is less clear if this code is in subclass B , where I can directly reference I using I :

 class C: B { constructor() { this.i = I {} } } 

So my questions are:

  • Why is this behavior happening at all?
  • If this happens, why does the compiler no longer raise an error?

PS: In android, the error message looks like this, which is even more confusing:

 Caused by: java.lang.NoSuchMethodError: No static method OnFocusChangeListener(Lkotlin/jvm/functions/Function2;)Landroid/view/View$OnFocusChangeListener; in class Landroid/widget/LinearLayout; or its super classes (declaration of 'android.widget.LinearLayout' appears in /system/framework/framework.jar:classes2.dex) 
+5
source share
1 answer

Define the main method as static like-

 companion object { @JvmStatic fun main(args: Array<String>) { A().i = BI {} } } 
0
source

Source: https://habr.com/ru/post/1269303/


All Articles