Null safety of Kotlin. Thought about a killer feature

Having got acquainted with the Kotlin language for the first time after a long time working with Java, I was turned back by the thought that null-safety can be useful and, in general, a variable without null is a primitive, but I myself did not realize it.





How it manifested itself:





  1. It is not convenient to work with variables and fields, which cannot have null. Well, I just didn’t even understand how something cannot be null.





  2. It is not convenient to work with nullable types. Well damn ?: !!





In general, time passed, slowly I began to get used to the fact that null might not exist, I even tried to do something idiomatic in my opinion: default values ​​in the form of an object ... In general, all this drove me into depression and I really wanted to write again in Java, since I'm used to living with null. As time passed, I already started to live normally with Kotlin's not nullable, as a friend one day I returned to Java ... And after a while I realized one thing:





When I work with legacy code (well, this is all the code that is generally written), then I do not understand where it can be null and where it can not, what makes me do a context switch from implementing business logic to finding out: can there be null?





Consider synthetics: We have a phone number entity with fields: a number, an international city code and a prefix (well, +7, +3, etc.), it was written before us, there is a mapping to the base, in general, everything is according to the canons of the bloody one. For business, all 3 fields of the phone number must be.





If I am in Java, then when working with this entity I have many options for how to use it:





  1. Use it as it is, without thinking about what's wrong with null (production will figure it out if we fix the bug)





  2. Get to the database and look at the constraint, thereby making sure that null cannot be there and you can safely use this entity without checks.





  3. With @NotNull annotations in place , press Ctrl + Q to see the description.





  4. Process all fields, assuming null can be everywhere.





  5. Write your own code, then deal with potential null.





  6. You can still think of options ...





, , , 5 - , . , NPE.





:





  1. null .





  2. null.





, .





, Java , : , , , !! ?:





Well, and once again about the null safety property itself: this is not quite a technical thing, rather it is about business, if in my business any value cannot be null, so let it fall in the early stages than live with some kind of null ...








All Articles