I'm trying to build an inline function for setOnFocusChangeListener
This is what I got so far:
inline fun EditText.onFocusChange(crossinline hasFocus: (Boolean) -> Unit) {
setOnFocusChangeListener(View.OnFocusChangeListener { view, b -> })
}
And I use it like this
freightTimeOfDay.onFocusChange { doSomething() }
Unfortunately though it gives me no errors, doSomething()
is never called.
I'm looking for two things here:
1 - Get a param in there so I can pass it on to doSomething(). For example
freightTimeOfDay.onFocusChange { doSomething(hasFocus) }
2 - Make it work :p, as right now nothing is happening.
Update:
Seems like kotlin already has some type of inline for this
editText.setOnFocusChangeListener { view, b -> doSomething(b) }
However this isn't working for me either, doSomething(hasFocus: Boolean)
is never called.
Thanks in advance!
The kotlin inline function is one of the types of function by using the keyword inline.
Go to: Tools -> Kotlin -> Show Kotlin Bytecode, then click the Decompile button. As we can see here, the doSomething () function is calling the doSomethingElse () function as usual. Now let's try to add the inline keyword as below in the doSomethingElse () function.
In Kotlin, the higher-order functions or lambda expressions, all stored as an object so memory allocation, for both function objects and classes, and virtual calls might introduce runtime overhead. Sometimes we can eliminate the memory overhead by inlining the lambda expression.
The mangling scheme has been changed in Kotlin 1.4.30. Use the -Xuse-14-inline-classes-mangling-scheme compiler flag to force the compiler to use the old 1.4.0 mangling scheme and preserve binary compatibility. You can call functions that accept inline classes from Java code.
Just to clarify, there isn't really a point in creating an inline method extension. This was my initial objective but I later realized that using:
editText.setOnFocusChangeListener { view, b -> doSomething(b) }
was possible, it's inline, it's pretty and no extra work is needed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With