Kotlin Extension Functions Databinding

user2725105 picture user2725105 · Apr 18, 2018 · Viewed 10.1k times · Source

Is there any possibility to use extension function with a databinding? XML:

<data>
    <import type="my.package.domain.country.model.City.streetName" />

    <variable
        name="city"
        type="my.package.domain.country.model.City" />
</data>

<TextView
    android:id="@+id/city"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{city.street.streetName()}" />

my.package.domain.country.model.city

data class City(
        val id: String,
        val street: Street
) 

fun City.streetName(): String = street.houseNumber

Error

[kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors. ****/ data binding error ****msg:cannot find method streetName() in class my.package.domain.country.model.City

Thanks ;)

Answer

skiff2011 picture skiff2011 · Aug 5, 2018

You have to import CityKt firstly into xml

<import type="my.package.domain.country.model.CityKt" />

int the data section then you can use it like this

<TextView
  android:id="@+id/city"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@{CityKt.streetName(city)}" />

If you review CityKt you will see that there is static Java method with City as first argument