Advantages of Scala's type system

后端 未结 2 1515
故里飘歌
故里飘歌 2021-01-29 17:42

I am exploring the Scala language. One claim I often hear is that Scala has a stronger type system than Java. By this I think what people mean is that:

2条回答
  •  感情败类
    2021-01-29 18:42

    The main safety problem with Java relates to variance. Basically, a programmer can use incorrect variance declarations that may result in exceptions being thrown at run-time in Java, while Scala will not allow it.

    In fact, the very fact that Java's Array is co-variant is already a problem, since it allows incorrect code to be generated. For instance, as exemplified by sepp2k:

    String[] strings = {"foo"};
    Object[] objects = strings;
    objects[0] = new Object();
    

    Then, of course, there are raw types in Java, which allows all sort of things.

    Also, though Scala has it as well, there's casting. Java API is rich in type casts, and there's no idiom like Scala's case x: X => // x is now safely cast. Sure, one case use instanceof to accomplish that, but there's no incentive to do it. In fact, Scala's asInstanceOf is intentionally verbose.

    These are the things that make Scala's type system stronger. It is also much richer, as VonC shows.

提交回复
热议问题