I understand you're talking about doing this for primitive types. All Java classes accept nulls as in C #. In Java only the primitive types do not accept null, as usually occurs with the ValueTypes
of C #.
C # has fixed a solution by encapsulating these types into a struct
named Nullable
. In it is the data you are working with and a * flag * indicating whether it is null or not, after all types by value can not have exceptional values, so extra information is needed. And the syntax of Tipo?
was created which in the background is translated to Nullable<Tipo>
when compiling.
There are two solutions for Java:
Use Integer
. It is a class, it can have a null reference. Something like this:
Integer inteiro = MetodoQualquer();
if (inteiro == null) {
// faz algo
} else {
// faz outra coisa
}
You can simulate this by creating a class that contains a flag indicating the condition of null
and the value itself. It's a very similar form to what I gave in that answer (obviously it would not have the primitive type, not a list). That is, you are reproducing what C # Nullable
does. But it does not have the Tipo?
syntactic sugar that C # has. It is not a good solution because Java does not have user defined%% types), but resolves.
There is still an option to use the structs
annotation but I believe it does not do exactly what you expect.
I did not mention the example of @Nullable
because unlike C # in Java this type is by reference, so it accepts DateTime
of course.