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

我有一个Kotlin错误说

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

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

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

我试过了:

  • buttonView: !CompoundButton, (说“期待逗号或)”)

  • buttonView: CompoundButton!, (说“意外令牌”)

  • buttonView!: CompoundButton, (说“期待逗号或)”)

  • !buttonView: CompoundButton, (说“期待逗号或)”)

  • buttonView: CompoundButton?, (表示“Expected 2 parameters of types android.widget.CompoundButton!,kotlin.Boolean”)

官方Kotlin文档说:

平台类型的表示法

如上所述,程序中不能明确提及平台类型,因此在语言中没有语法。 然而,编译器和IDE有时需要显示它们(在错误消息,参数信息等中),所以我们对它们有一个助记符:

  • 牛逼! 意思是“T或T?”,

  • (可变)收藏! 意思是“T的Java集合可以是可变的或不可以的,可以是可以不可以的”,

  • 数组<(出)T>! 是指“T(或T的子类型)的Java数组,可为空或不是”

我不完全明白这些文件是在说什么。 我将如何解决这个错误?

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

请参阅对象声明

尝试这个:

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

希望这可以帮助

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

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

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