Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Extension Functions Databinding

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 ;)

like image 219
user2725105 Avatar asked Apr 18 '18 11:04

user2725105


People also ask

What is databinding in Kotlin?

The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. Layouts are often defined in activities with code that calls UI framework methods.

What are Kotlin extension functions?

Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any type of design pattern. The created extension functions are used as a regular function inside that class. The extension function is declared with a prefix receiver type with method name.

When would you use Kotlin extension function?

In particular, Kotlin extensions let you add functions to a class that you cannot modify. By using them, you will be able to call these new functions as if they were part of the original class. Similarly, you can use this mechanism to add new properties to existing classes. You can also extend Kotlin companion objects.

What is extended function?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.


1 Answers

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

like image 195
skiff2011 Avatar answered Sep 20 '22 16:09

skiff2011