Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that only ever returns null in Kotlin

Tags:

kotlin

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.

like image 993
Casebash Avatar asked Mar 11 '18 01:03

Casebash


People also ask

How do I return a null value in Kotlin?

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.

Can a function return 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.

What is nullable Kotlin?

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 .

How do you ensure null safety in Kotlin?

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.


1 Answers

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 is null. If you use null 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 the Nothing? type:

val x = null           // 'x' has type `Nothing?`
val l = listOf(null)   // 'l' has type `List<Nothing?>
like image 54
s1m0nw1 Avatar answered Oct 23 '22 05:10

s1m0nw1