1

Is it possible to use methods from Kotlin stdlib in xml? For example this code

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:textColor="#333333"
    android:text="@{viewModel.note}"
    android:visibility="@{viewModel.note.isNotEmpty ? View.VISIBLE : View.GONE}"/>

produce compilation error

Execution failed for task ':app:compileDevDebugJavaWithJavac'. java.lang.RuntimeException: Found data binding errors. ****/ data binding error ****msg:cannot find method isNotEmpty() in class java.lang.String file:D:\Projects\PushTracker-Android\app\src\main\res\layout\fragment_appointment_simple_details.xml loc:104:44 - 104:70 ****\ data binding error ****

It is obvious that databinding tries to find method isNotEmpty() in Java's String but can I force databinding compiler to use kotlin's String?

yennsarah
  • 5,467
  • 2
  • 27
  • 48
hluhovskyi
  • 9,556
  • 5
  • 30
  • 42

1 Answers1

2

"kotlin's String" does not exist. Kotlin's standard library defines extension methods to create the method you're referring to. But since the data-binding library needs to generate Java code it cannot find the method you're referring to.

In order to use that method you will need to call it using the way Java would call it, which is as a static function:

kotlin.text.StringsKt.isNotEmpty(viewModel.note)

EDIT: this method is annotated with @InlineOnly, so this method might not exist outside of Kotlin code.

Kiskae
  • 24,655
  • 2
  • 77
  • 74
  • 1
    Yes, i've tried this but also stucked with `@InlineOnly`. As I understand there is only one solution - define this methods in some helper object with `@JvmStatic` – hluhovskyi Apr 06 '17 at 13:01
  • 1
    @Google `@JvmStatic` is not necessary, you'll be able to call the method anyway. The recommended way is to use a file-level function thou, not an object method. – voddan Apr 07 '17 at 06:17