Kotlin DataBinding pass static function into layout xml

Utilities are generally created as Kotlin File. Because Kotlin files methods are global. Which you can use from anywhere without making it @JvmStatic.

BindingAdapterDefault.kt

fun formatUnixTime(timeInSeconds: Long, pattern: String): String {
    val simpleDateFormat = SimpleDateFormat(pattern, Locale.US)
    return simpleDateFormat.format(Date(timeInSeconds * 1000))
}

That will work for you same, NO class, brackets, companion, object etc...

From XML

<import type="com.innovanathinklabs.sample.ui2.BindingAdapterDefaultKt"/>

android:text="@{BindingAdapterDefaultKt.formatUnixTime(1540966388,`hh:mm:ss`)}"

That's all you need.

I want add more info about this. You can directly call this method from Java and Kotlin too.

From Java class

import static com.package.BindingAdapterDefaultKt.formatUnixTime;
formatUnixTime(454545, "hh:mm:ss");

From Kotlin class

import com.package.formatUnixTime
formatUnixTime(454545, "hh:mm:ss");

Suggestion

I prefer creating BindingAdapter which was introduced with Data Binding, and is very powerful thing. It gives me more flexibility across the app.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:formatSeconds="@{1540966388}"
    app:pattern="@{`hh:mm:ss`}"
    />

BindingAdapterDefault.kt

@BindingAdapter(value = ["formatSeconds", "pattern"])
fun secondsToDateText(textView: TextView, timeInSeconds: Long, pattern: String) {
    val simpleDateFormat = SimpleDateFormat(pattern, Locale.US)
    textView.text = simpleDateFormat.format(Date(timeInSeconds * 1000))
}

Have you tried adding @JvmStatic annotation? It should help!

From official source:

Specifies that an additional static method needs to be generated from this element if it's a function. If this element is a property, additional static getter/setter methods should be generated.