首页 文章

Kotlin错误:预期2个类型的参数android.widget.CompoundButton!,kotlin.Boolean

提问于
浏览
1

我有一个Kotlin错误说

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

红色波浪线在下面的代码中的第一个 {

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

我试过了:

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

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

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

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

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

官方Kotlin文档说:

平台类型的表示法如上所述,程序中无法明确提及平台类型,因此语言中没有语法 . 然而,编译器和IDE有时需要显示它们(在错误消息,参数信息等),所以我们有一个助记符号:T!意思是“T或T?”,(可变)收藏!意思是“T的Java集合可能是可变的,也可能是可空的”,Array <(out)T>!表示“T的Java数组(或T的子类型),可以为空”

我不完全理解文档的内容 . 我该如何解决这个错误?

2 回答

  • 1

    我认为你需要创建匿名类对象所需的object关键字( object: ) .

    Object declaration

    试试这个:

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

    希望这可以帮助

  • 1

    我们还可以使用lambda表达式简化代码

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

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

相关问题