我试图在kotlin中创建一个简单的未绑定服务,但我做不到.当我在Java中重写onBind()方法时,我可以返回null,但在kotlin中,它说我只能返回IBinder,不能返回IBinder?,这意味着它不能是null.除了将MyService类重写为Java之外,还有其他解决方法吗?

[SOLVED] Thank you, guys! I can realy change IBinder to IBinder?. It works!!

推荐答案

正如Enrico提到的,您可以将类型IBinder更改为IBinder?,它仍将与接口匹配.

下面是一个例子:

override fun onBind(intent: Intent): IBinder? {
   return null
}

通常,使用Android Studio覆盖Android方法时要小心.当系统实际上可以返回空引用时,当它生成非空类型时,真正的问题出现了.它会导致您确实没有预料到的运行时Kotlin异常.

如果我没记错的话,我在重载Fragment个类和View个创建相关的方法时遇到了很多问题.

Kotlin相关问答推荐

Compose:LaunchedEffect在密钥更改后不会重新启动

在Kotlin 有更好的结合方式?

Kotlin Coroutine()是如何工作的?S阻止了.

generic 类实例列表 - 调用采用 T 的函数

如何在 Android Jetpack Compose 中的画布上绘制一侧加厚的描边?

interface扩展

来自类型参数的属性的自定义 getter

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

Kotlin内联扩展属性

在kotlin中,如何模拟封装回调函数?

Jacoco在Gradle 7.0.2和Kotlin 1.5.10上失败

Kotlin中的Memoization功能

在kotlin中初始化类变量的正确位置是什么

如何序列化/反序列化Kotlin密封类?

安装 Kotlin-Jupyter:e: java.lang.NoClassDefFoundError: 无法初始化类 org.jetbrains.kotlin.com.intellij.pom.java.LanguageLevel

Kotlin内联属性的用例是什么?

将 androidx.constraintlayout:constraintlayout lib 更新到 2.0.2 版本后出现崩溃 isRtl () null 引用

Android Jetpack Compose 中的文本渐变

从另一个列表创建一个列表

函数引用和lambdas