Add optional parameter to Android Kotlin class

In general you would provide no-op or null-value implementations like

neutralButtonText: String = ""
neutralButtonListener: OnClickListener = OnClickListener {}

But in your use-case you must not use constructor parameters at all!

Fragments can be recreated from the system and require a default constructor.

You need to communicate with the activity or parentFragment by letting these implement the interface you require.


Check this out

class AlertDialogFragment(  
    context: Context,  
    val positiveButtonText: String,  
    val positiveButtonListener: DialogInterface.OnClickListener,  
    val negativeButtonText: String,  
    val negativeButtonListener: DialogInterface.OnClickListener,  
    neutralButtonText: String = "",  
    neutralButtonListener: DialogInterface.OnClickListener ?= null
) : DialogFragment() { }

You may try this:

class AlertDialogFragment(
    context: Context,  
    val positiveButtonText: String,  
    val positiveButtonListener: DialogInterface.OnClickListener,  
    val negativeButtonText: String,  
    val negativeButtonListener: DialogInterface.OnClickListener,  
    neutralButtonText: String = "",  
    neutralButtonListener: DialogInterface.OnClickListener = OnClickListener {}  
) : DialogFragment() { }

Default parameters to the rescue.

class AlertDialogFragment(
    context: Context,
    val positiveButtonText: String,
    val positiveButtonListener: DialogInterface.OnClickListener,
    val negativeButtonText: String,
    val negativeButtonListener: DialogInterface.OnClickListener, 
    neutralButtonText: String = "",
    neutralButtonListener: DialogInterface.OnClickListener = OnClickListener {}
) : DialogFragment()

Basically, Kotlin will generate multiple methods, for each combination of parameters possible.

If could also be better to include @JvmOverload annotation on the constructor to allow the same thing in Java.

Tags:

Android

Kotlin