Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin “toString()” Not Available in Android DataBinding

Just learned DataBinding and find out that the powerful built-in toString() from Kotlin is not available:

<layout 
    xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="student"
            type="com.example.databindingtest2.Student" />

    </data>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{student.name}"
        android:textColor="@android:color/black"
        android:textSize="30sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@{student.age.toString()}"    //doesn't work, age is integer
        android:textColor="@android:color/black"
        android:textSize="30sp" />

</layout>

I know String.valueOf() will work, but it's not Kotlin way. Any help would be appreciated.

like image 989
Sam Chen Avatar asked Oct 15 '25 22:10

Sam Chen


2 Answers

doesn't work, age is integer

There is no type in either Java or Kotlin named integer. I am going to guess that age is a Kotlin Int.

cannot find method toString() in class int

Data binding is implemented in Java, not Kotlin. Java/Kotlin interoperability, combined with the data binding compiler, appears to be converting the Kotlin Int into the Java int primitive type. Java primitives do not extend Object and do not have toString().

Personally, I recommend not investing in data binding. Jetpack Compose will make data binding obsolete in a year or so.

If you still wish to use data binding, the simplest solution is String.valueOf(). While you say "it's not Kotlin way", you are working with data-binding-generated Java, not Kotlin.

If you still wish to use data binding, and you insist that you must use toString()... try @{Integer.valueOf(student.age).toString()}. Integer.valueOf() will give you a Java Integer instance boxing your int, and Integer has a toString() method. This still has nothing really to do with Kotlin, but it would let you use toString().

like image 100
CommonsWare Avatar answered Oct 17 '25 11:10

CommonsWare


One month later, I found this trick:

android:text="@{`` + viewModel.currentStudent.age}"     //"``" is key point!! Not single/double quote
like image 25
Sam Chen Avatar answered Oct 17 '25 12:10

Sam Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!