Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add optional parameter to Android Kotlin class

Tags:

android

kotlin

I've created an extension of DialogFragment():

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

however I want the last 2 parameters to be optional.

How can I achieve this?

I can't set neutralButtonListener: DialogInterface.OnClickListener = null because DialogInterface.OnClickListener is a non null type.

like image 493
Zorgan Avatar asked Jun 07 '19 06:06

Zorgan


1 Answers

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.

like image 174
shkschneider Avatar answered Sep 28 '22 07:09

shkschneider