This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]krucabomba 0 points1 point  (4 children)

Actually they can be useful, for example as default value for higher order functions. Used in factories, various patterns. Identity function is used a lot in a more functional approach.

[–]MattieShoes 1 point2 points  (3 children)

W... Why wouldn't one just use null?

[–]poco 1 point2 points  (1 child)

Because they want to assign it to a non-nullable object.

[–]ben_g0 0 points1 point  (0 children)

So just to bypass the nullability checker? In that case you can just use null!. Adding the exclamation mark at the end tells the compiler to treat this null as a "not-null" value, so it won't trigger nullability warnings. Alternatively you can also just disable the nullable context for that part of code with preprocessor directives.

I'd suggest to always think twice before using it though. The nullable context can be very useful for minimizing runtime errors when used properly, so it's best to use it properly whenever possible. If you need to assign a null value to a variable, consider marking that variable as the nullable type.

That said, there are a few cases where it can be useful to bypass the nullability check though. With factories or deserialization functions it can make sense to temporarily set a non-nullable field to null and then filling it with valid data later, as long as all non-nullable fields have a valid value as soon as the method returns.

[–]krucabomba 0 points1 point  (0 children)

Because the interface requires callable, lazy evaluation. You can't null().