Java interface to Kotlin function callback with android example
A simple example of converting java interface callback into Kotlin function callback.
For example, in java, we use to interface to get a callback inside to do some work. In java,
First, need to declare an interface,
interface OnDialogOkClickListener {
fun onDialogOkClicked()
}
Then the implementation will be,
// In java 7
showPrompt("title", "message", new OkDialogOkLisneter() {
@Override
public void onOkClicked() {
// Do something you here want when user click ok in prompt
}
})// In Java 8
showPrompt("title", "message",() -> {
// Do something you here want when user click ok in prompt
})
When you use interface method in kotlin. we will get following
showPrompt("title", "message", object : OnDialogOkClickListener {
override fun onDialogOkClicked() {
// Do something you here want when user click ok in prompt
}
})
Its look like quite a lot of lines and need to declare an interface, So instead of using interface callback if we use the function as the callback, it will end up like the below example
showPrompt("title", "message") {
// Do something you here want when user click ok in prompt
}
Look fancy nha ;)
Let's see how to do it!
Before seeing how to do let's discuss
What is it actually?
Short answer — Its called HIGHER-ORDER Function
And the brief
In Kotlin functions are first-class which means that they can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. A higher-order function is a function that takes functions as parameters, or returns a function. Read more in official doc here goo.gl/GqArF9
Below example shows how to display prompt some information to user and do some work when the user clicks ok.
So the dialogFragment,
class CustomDialogFragment(val title: String, val message: String ,val okClickListener: () -> Unit) : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog? {
val title = arguments!!.getString(title)
val alertDialogBuilder: AlertDialog.Builder = Builder(activity)
alertDialogBuilder.setTitle(title)
alertDialogBuilder.setMessage(message)
alertDialogBuilder.setPositiveButton("YES", DialogInterface.OnClickListener { dialog, which ->
// on success
okClickListener.invoke()
})
alertDialogBuilder.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, which ->
if (dialog != null && dialog.isShowing()) {
dialog.dismiss()
}
})
return alertDialogBuilder.create()
}
}
That's it!!!
We can use this like below.
CustomDialogFragment("Alert", "Are you hungry?") {
// do task when 'yes' clicked
}.show(supportFragmentManager, "dialog")
Conclusion
Still most of cases we required interfaces so this is one of the approaches this will embrace the Kotlin standard.
References: