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

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.

主站蜘蛛池模板: 黄梅县| 通榆县| 航空| 平顺县| 仁寿县| 安丘市| 古交市| 华阴市| 都江堰市| 洛宁县| 南开区| 济阳县| 佛冈县| 禄丰县| 北辰区| 岳阳市| 盐源县| 井研县| 盐池县| 廊坊市| 芜湖县| 凉山| 本溪市| 松原市| 保定市| 博客| 开阳县| 裕民县| 宁化县| 木里| 保康县| 雅江县| 桦南县| 商洛市| 南昌县| 万州区| 汉源县| 宽城| 乐清市| 云安县| 昭通市|