3

I have a Kotlin error saying

Expected 2 parameters of types android.widget.CompoundButton!, kotlin.Boolean

The red squiggly line is at the first { in the code below:

    alarmSwitch.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener()
    { 
        fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean)
        {

I tried:

  • buttonView: !CompoundButton, (says "Expecting comma or )" )

  • buttonView: CompoundButton!, (says "Unexpected Token")

  • buttonView!: CompoundButton, (says "Expecting comma or )" )

  • !buttonView: CompoundButton, (says "Expecting comma or )" )

  • buttonView: CompoundButton?, (says "Expected 2 parameters of types android.widget.CompoundButton!, kotlin.Boolean" )

The official Kotlin docs say:

Notation for Platform Types

As mentioned above, platform types cannot be mentioned explicitly in the program, so there’s no syntax for them in the language. Nevertheless, the compiler and IDE need to display them sometimes (in error messages, parameter info etc), so we have a mnemonic notation for them:

  • T! means “T or T?”,

  • (Mutable)Collection! means “Java collection of T may be mutable or not, may be nullable or not”,

  • Array<(out) T>! means “Java array of T (or a subtype of T), nullable or not”

I don't fully understand what the docs are saying. How would I fix this error?

3 Answers 3

3

We can also simplify the code using a lambda expression

alarmSwitch.setOnCheckedChangeListener { buttonView, isChecked -> /* whatever...*/ }

https://antonioleiva.com/functional-programming-android-kotlin-lambdas/

Sign up to request clarification or add additional context in comments.

Comments

1

I think you need the object keyword (object:) which is needed for creating an object of an anonymous class.

See Object declaration

Try this:

alarmSwitch.setOnCheckedChangeListener(object:OnCheckedChangeListener() {
  fun onCheckedChanged(buttonView:CompoundButton, isChecked:Boolean) {
    // whatever...
  }
})

Hope this helps

Comments

0
checkboxQuickApproval.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener {
   override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        if (isChecked) {
            viewModel.onChangeCheckboxValue(isChecked) 
        }
    }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.