U
U
user_of_toster2022-01-18 14:58:16
Programming
user_of_toster, 2022-01-18 14:58:16

What are the pros and cons of being able to return null instead of a return type?

Example in Typescript:

function getStringsArray(): string[] {
    return null // Type 'null' is not assignable to type 'string[]';
}

Java example:
public static String[] getStringsArray() {
    return null; // OK
}

With the first option, constant checks for null will not be required in the code, you can be sure that the result will be a string.

In the second option, it is easier for the creator of the method to pass null if the object does not exist, but consumers will have to do checks.

Are there other pros and cons? I want to understand what the creators of the language were guided by when making this decision

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2022-01-18
@user_of_toster

Nullable references in Java are a billion-dollar mistake.
There are no advantages to this, it's just that at the time of development there was no thought that optional types should be added to the type system. Later, they tried to solve this with annotations like NotNull / Nullable, but they do not completely solve the problem, and besides, they are very verbose.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question