Home > Mobile >  Kotlin - The feature "unit conversion" is disabled
Kotlin - The feature "unit conversion" is disabled

Time:05-15

I am still a relative newbie at Kotlin and, after a fair bit of digging, cant fix what looks to be a simple problem. For the code below the compiler returns: The feature "unit conversion" is disabled for "function = positiveButtonClick" and function = negativeButtonClick"

Why? What do I need to do?

Thanks

    called with MessageBox(context, "Hello Test", "My Message");


    fun MessageBox(contxt: Context?, title: String, message: String): Boolean {

        val builder = AlertDialog.Builder(contxt)

        with(builder) {
            setTitle(title)
            setMessage(message)
            setPositiveButton("YES", DialogInterface.OnClickListener(function = positiveButtonClick))
            setNegativeButton("NO",  DialogInterface.OnClickListener(function = negativeButtonClick))
            show()
        }

        return false
    }


    val positiveButtonClick = { dialog: DialogInterface, which: Int -> Unit
        Log.i("Dialog", "Yes")
    }

    val negativeButtonClick = { dialog: DialogInterface, which: Int -> Unit
        Log.i("Dialog", "No")
    }

CodePudding user response:

Don't really know what this error means maybe a version Specific stuff which they changed later . i can't say for sure.

To solve this you can directly pass listeners with modifying the lambda with interface name i.e DialogInterface.OnClickListener .

fun MessageBox(contxt: Context?, title: String, message: String): Boolean {
    val builder = AlertDialog.Builder(contxt)
    with(builder) {
        setTitle(title)
        setMessage(message)
        setPositiveButton("YES", positiveButtonClick)
        setNegativeButton("NO",  negativeButtonClick)
        show()
    }
    return false
}
val positiveButtonClick = DialogInterface.OnClickListener{ dialog: DialogInterface, which: Int -> Unit
    Log.i("Dialog", "Yes")
}
val negativeButtonClick = DialogInterface.OnClickListener{ dialog: DialogInterface, which: Int -> Unit
    Log.i("Dialog", "No")
}

CodePudding user response:

I found the answer in the Kotlin documentation (High-order functions and lambdas) but only by chance. In the example code there was a comment line

// The last expression in a lambda is considered the return value:

so simply adding Unit as the last line in the lambda fixed the problem by forcing it to return Unit

val positiveButtonClick = { dialog: DialogInterface, which: Int -> Unit
   Log.i("Dialog", "Yes")
   Unit
}
  • Related