- Kotlin Blueprints
- Ashish Belagali Hardik Trivedi Akshay Chordiya
- 426字
- 2021-07-02 21:50:09
Enhanced robustness
Statically typed languages have a built-in safety net because of the assurance that the compiler will catch any incorrect type cast. Both Java and Kotlin support static typing.
With Java Generics introduced in Java 1.5, they both fare better over the Java releases prior to 1.5.
However, Kotlin takes a big step further in addressing the Null pointer error. This Null pointer error causes a lot of checks in Java programs:
String s = someOperation(); if (s != null) { ... }
One can see that the null check is not needed if someOperation() never returns null. On the other hand, it is possible for a programmer to omit the null check while someOperation() returning null is a valid case.
With Kotlin, the definition of someOperation() itself will return either String or String? and then there are implications on the subsequent code, so the developer just cannot go wrong. Refer the following table:

One may point out that Java developers can use the @Nullable and @NotNull annotations or the Optional class; however, these were added quite late, most developers are not aware of them, and they can always get away with not using them, as the code does not break. Finally, they are not as elegant as putting a question mark.
There is also a subtle point here. If a Kotlin developer is careless, he would write just the type name, which would automatically become a non-nullable declaration. If he wanted to make it nullable, he would have to key in that extra question mark deliberately. Thus, you are on the side of caution, and that is as far as keeping the code robust is concerned.
Another example of this robustness is found in the var/val declarations. Seasoned programmers know that most variables get a value assigned to them only once. In Kotlin, while declaring the variable, you choose val for such a variable. At the time of variable declaration, the programmer has to select between val and var, and so he puts some thought into it. On the other hand, in Java, you can get away with just declaring the type with its name, and you will rarely find any Java code that defines a variable with the final keyword, which is Java's way of declaring that the variable can be assigned a value only once.
Basically, with the same maturity level of programmers, you expect a relatively more robust code in Kotlin as opposed to Java, and that's a big win from the business perspective.
- C語言程序設計實踐教程(第2版)
- 數字媒體應用教程
- GitLab Repository Management
- Python神經網絡項目實戰
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(高級進階篇)
- Getting Started with Gulp
- Learning Concurrency in Kotlin
- Python圖形化編程(微課版)
- Geospatial Development By Example with Python
- Emgu CV Essentials
- MATLAB GUI純代碼編寫從入門到實戰
- Python青少年趣味編程
- 零基礎學HTML+CSS第2版
- Ext JS 4 Plugin and Extension Development
- 深度實踐KVM:核心技術、管理運維、性能優化與項目實施