官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 桓仁| 车险| 屏南县| 达孜县| 嘉禾县| 罗山县| 常熟市| 福海县| 阿拉善盟| 延长县| 四会市| 科尔| 万全县| 鲁山县| 屏东市| 治县。| 维西| 云和县| 泰和县| 云浮市| 读书| 宝山区| 肇庆市| 丰原市| 永安市| 漯河市| 柘荣县| 高安市| 淮阳县| 宁安市| 闸北区| 拉萨市| 黔西| 吉木萨尔县| 尤溪县| 天祝| 富宁县| 成都市| 金平| 聊城市| 海兴县|