Kotlin 错误 : Expected 2 parameters of types android. widget.CompoundButton!, kotlin.Boolean

标签 kotlin

我有一个 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!,(显示“意外 token ”)

  • buttonView!: CompoundButton,(表示“期望逗号或)”)

  • !buttonView: CompoundButton,(表示“期望逗号或)”)

  • buttonView: CompoundButton?,(表示“预期 2 个类型为 android.widget.CompoundButton 的参数!,kotlin.Boolean”)

官方 Kotlin 文档说:

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”

我不完全理解文档在说什么。我该如何解决这个错误?

最佳答案

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

参见 Object declaration

试试这个:

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

希望对你有帮助

关于Kotlin 错误 : Expected 2 parameters of types android. widget.CompoundButton!, kotlin.Boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34146508/

相关文章:

android - Kotlin:如何让 searchView 提交

Kotlin SharedFlow - 如何订阅?

java - JOOQ with Gradle 和 Kotlin 不生成文件

java - 在 Kotlin/Java 中寻找 .properties 和 .y(a)ml 文件的属性解析器,就像在 Spring 中一样

java - 在 Java/Kotlin 中生成 ed25519 key

android - Dagger 2 : ViewModel cannot be provided without an @Provides-annotated method

android - 为什么我们不能在 jetpack compose 的 mutableStateListOf 中使用 delegate 属性

swift - Kotlin 相当于 Swift 的排序(按 :)

android - 当我尝试动态创建 LinearLayout 时,无法重新分配 Val

java - 在Android上读取jpeg文件的量化表