DEV Community

Discussion on: Nulls and null checks - How to work safely with nulls in any codebase

Collapse
 
sargalias profile image
Spyros Argalias

Hmm, thanks for raising that point. To make sure I'm understanding it: Do you mean that, after you define a variable as a string, you can never assign it to null? So you don't need a null check in that case? And that maybe I should mention that in the article?

If so, then that's a good point. I might modify the article a bit and add that example. TypeScript also has the same feature.

Thank you.

Collapse
 
nfrankel profile image
Nicolas Frankel
val canBeNull: String? = null
val cannotBeNull: String = "Foo"
Enter fullscreen mode Exit fullscreen mode

In the above code, the compiler will fail if you if you try to use canBeNull without applying null checks first. In the second case, it won't because... well, it cannot be null.

Note that I explicitly set the type on the second variable though it's not necessary for better readability.

Thread Thread
 
sargalias profile image
Spyros Argalias

Thanks for the clarification. I modified that section to mention non-nullable types and credited you for pointing them out.

Please let me know if you don't want the credit or if you'd rather be credited in a different way.

Thread Thread
 
nfrankel profile image
Nicolas Frankel

I didn't expect credit so that's very fine, thanks!