Is it possible to declare a function that only ever returns null
? Unfortunately, you cannot write null
in the return type section. The return value should be null
and not Unit so that it can work with nullable operators.
In Kotlin, there are optional types. If you return ServiceChargeMasterList, you say to the compiler that you will never return null. If you want to return null, you have to add ? sign at the end of the type which indicates that you can return an instance of ServiceChargeMasterList or null.
If your function is usually returns something but doesn't for some reason, return null; is the way to go. That's similar to how you do it e.g. in C: If your function doesn't return things, it's void , otherwise it often return either a valid pointer or NULL.
In Kotlin, there's a distinction between nullable and non-nullable types: Nullable types are variables that can hold null . Non-null types are variables that can't hold null .
Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.
As also suggested in the comments, Nothing?
should be the return type of such a function:
fun alwaysNull(): Nothing? = null
The documentation states:
[...] Another case where you may encounter this type is type inference. The nullable variant of this type,
Nothing?
, has exactly one possible value, which isnull
. If you usenull
to initialize a value of an inferred type and there's no other information that can be used to determine a more specific type, the compiler will infer theNothing?
type:val x = null // 'x' has type `Nothing?` val l = listOf(null) // 'l' has type `List<Nothing?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With