Kotlin返回Null不能是非null类型的值 [英] Kotlin Returning Null cannot be a value of a non-null type

查看:89
本文介绍了Kotlin返回Null不能是非null类型的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Kotlin函数返回一个空值.它给我错误Null cannot be a value of a non-null type.但我希望能够返回null.尽管看起来函数可以为空,但它是接口重写,在这种情况下,没有返回值.

I am trying to return a null value for a Kotlin function. It gives me the error Null cannot be a value of a non-null type. But I want to be able to return null. Although it looks the function can be void, it is an interface override and in this case there is no return value.

override fun call(jso: JSONObject): JSONObject {
    ...
    ...
    return null
}

我想我可以使用?将变量标记为可为空.但是在这种情况下,我可以将?放在哪里?

I guess I can mark a variable nullable using ?. But where can I put the ? in this case?

推荐答案

您必须将?放在返回类型之后:

You have to put the ? after the return type:

override fun call(jso: JSONObject): JSONObject? {
    ...
    return null
}

由于具有override修饰符,因此还需要更改超类方法的返回类型.

Since you have the override modifier, you also need to change the return type of the super class method.

这篇关于Kotlin返回Null不能是非null类型的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆