2

I was wondering if there is any way we can call extensions in expression attribs,

For Eg, here is some extension

fun String.parseServerDate():String{
 ...
}

To call while in kotlin, we use myTime.parseServerDate()

So, my problem is how can I call this extension within in expression language

Tried @{mydate.parseServerDate()} which is not working

I tried importing my extension kt file in <import> tag, but nothing seems to be happening

Aziz
  • 1,976
  • 20
  • 23
  • 1
    Possible duplicate of [Kotlin databinding with extension methods](https://stackoverflow.com/questions/52589320/kotlin-databinding-with-extension-methods) – Daniel Sep 30 '19 at 10:43
  • Please post your xml file and consider reading about Binding adapters: https://developer.android.com/topic/libraries/data-binding/binding-adapters – Giorgos Neokleous Sep 30 '19 at 10:49

2 Answers2

2

You can't use extension functions in XML

what you can do is create a data binding adapter for whatever you want to do with the view or make an object and put the function inside it so you can use it where ever you like

object Functions{
   fun parseServerDate(string : String) {
   ...
   }
}



//in xml

<import type="the object path"/>

@{Functions.parseServerDate(data.string)}

in order for me to help you more you must be more specific about what you want to do i.e what the extension function does

you can read about binding adapters here https://developer.android.com/topic/libraries/data-binding/binding-adapters

0

Let us say your extension method is defined in ExtensionMethod.kt Import the kt file like so

<import type="yourpackage.ExtensionMethodKt"/>

Then while calling your extension use the below format

@{ExtensionMethodKt.parseServerDate(mydate)}

This should solve your problem!

rbd_sqrl
  • 420
  • 4
  • 14
  • Perhaps you should read the last line of my question, I already tried this but it won't work – Aziz Sep 30 '19 at 10:55
  • @Aziz After importing are you calling your extension fun like `@{mydate.parseServerDate()}` or `@{ExtensionMethodKt.parseServerDate(mydate)} `? – rbd_sqrl Sep 30 '19 at 10:59
  • @Aziz Check this post if you haven't already. - https://stackoverflow.com/questions/49898669/kotlin-extension-functions-databinding – rbd_sqrl Sep 30 '19 at 11:12