简体   繁体   中英

What is the difference between Java static method and Kotlin companion object ? Why it is giving error in Andorid Data Binding?

Hi Guys I have one scenario, where I am working with Android data binding . I am trying to bind one small util method to the view as bellow

//Java Code
    public class Util {
            public static String capitalize(String text) {
                return text.toUpperCase();
            }
    }

And Xml Layout code as bellow

//layout.xml--Android
    <data>
        <import type="com.lkb.baseandroidproject.Util"/>
    </data>

...

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{Util.capitalize(user.name)}"/>

It is woking fine, but when I am converting the Java class to kotlin as

class Util {
    companion object {
        fun capitalize(text:String): String {
            return text.toUpperCase()
        }
    }
}


 <TextView  android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@{Util.Companion.capitalize(user.name)}"/>

It is giving the error

[kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:cannot find method capitalize(java.lang.String) in class com.lkb.baseandroidproject.Util.Companion file:/Users/leo/code/Android/Android_projects/Android_projects/BaseAndroidProject/app/src/main/res/layout/content_main.xml loc:23:32 - 23:68 ****\ data binding error ****

    at android.databinding.tool.processing.Scope.assertNoError(Scope.java:112)
    at android.databinding.annotationprocessor.ProcessDataBinding.doProcess(ProcessDataBinding.java:109)
    at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:73)
    at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:99)

The bytecode generated by your Kotlin code is as follows (Kotlin 1.3):

public final class com/example/testapp/Util$Companion {
  // access flags 0x11
  public final capitalize(Ljava/lang/String;)Ljava/lang/String;

As you can see an inner class Companion is being created, which actually has the method capitalize .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM