Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to NOT pass arguments to parameters with default values in Data Binding

Is it possible to call Kotlin function with default parametrs from XML without passing arguments

This is my ViewModel:

class MyViewModel: ViewModel(){

    fun doSomething(myVar: String = "defValue"){

    }
}

XML:

....
<data>
    <variable
        name="viewModel"
        type="com.example.MyViewModel" />
</data>
....
android:onClick="@{(view) -> viewModel.doSomething()}"  --> ERROR
android:onClick="@{(view) -> viewModel.doSomething(`SomeString`)}"  --> WORKING
....

When I call the doSomething method without argument from XML with Data Binding I am getting error.

[databinding] {"msg":"cannot find method doSomething() in class com.example.MyViewModel","file":"app\\src\\main\\res\\layout\\fragment_list.xml","pos":[{"line0":56,"col0":41,"line1":56,"col1":65}]}
like image 328
SpiralDev Avatar asked Jul 03 '20 06:07

SpiralDev


1 Answers

Annotate your Kotlin method with @JvmOverloads. Java does not have a concept of default parameters. This annotation has the Kotlin compiler generate a no-argument method, so you can call it from Java and from your databinding XML in turn.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-overloads/

like image 136
Uli Avatar answered Nov 01 '22 12:11

Uli