Kotlin"toString()"在Android DataBinding中不可用 [英] Kotlin “toString()” Not Available in Android DataBinding

查看:248
本文介绍了Kotlin"toString()"在Android DataBinding中不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅学习了DataBinding,发现没有Kotlin强大的内置toString():

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>

我知道String.valueOf()可以工作,但不是Kotlin方式.任何帮助将不胜感激.

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

推荐答案

doesn't work, age is integer

Java或Kotlin中没有名为integer的类型.我猜想age是科特林Int.

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

数据绑定是用Java实现的,而不是Kotlin. Java/Kotlin互操作性与数据绑定编译器结合在一起,似乎正在将Kotlin Int转换为Java int原语类型. Java原语不扩展Object并且不具有toString().

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().

就个人而言,我建议不要投资于数据绑定. Jetpack Compose将使数据绑定在一年左右的时间内过时.

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

如果您仍然希望使用数据绑定,则最简单的解决方案是String.valueOf().当您说这不是Kotlin的方式"时,您正在使用的是数据绑定生成的Java,而不是Kotlin.

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.

如果您仍然希望使用数据绑定,并且坚持必须使用toString() ...,请尝试@{Integer.valueOf(student.age).toString()}. Integer.valueOf()将为您提供一个Java Integer实例,将您的int装箱,而Integer具有toString()方法.这仍然与Kotlin无关,但可以让您使用toString().

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().

这篇关于Kotlin"toString()"在Android DataBinding中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆