Reputation: 2069
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?
Upvotes: 1
Views: 3584
Reputation: 461
For those who are facing the same problem I did in regards to null being able to be returned even though you changed the return type to say for example JSONObject? by getting an error:
Return type is 'JSONObject?', which is not a subtype of overridden public abstract...
Simply do this:
override fun call(jso: JSONObject): JSONObject {
...
throw Exception("Error message!")
}
Upvotes: 0
Reputation: 7544
You have to put the ?
after the return type:
override fun call(jso: JSONObject): JSONObject? {
...
return null
}
Since you have the override
modifier, you also need to change the return type of the super class method.
Upvotes: 6