简体   繁体   English

Scala类型系统的优点

[英]Advantages of Scala's type system

I am exploring the Scala language. 我正在探索Scala语言。 One claim I often hear is that Scala has a stronger type system than Java. 我经常听到的一个主张是Scala具有比Java 更强大的类型系统。 By this I think what people mean is that: 通过这个我认为人们的意思是:

  • scalac rejects certain buggy programs which javac will compile happily, only to cause a runtime error. scalac拒绝某些错误的程序, javac会愉快地编译,只会导致运行时错误。
  • Certain invariants can be encoded in a Scala program such that the compiler won't let the programmer write code that violates the condition. 某些不变量可以在Scala程序中编码,这样编译器就不会让程序员编写违反条件的代码。

Am I right in thinking so? 我这么认为是对的吗?

The main advantage of the Scala Type system is not so much being stronger but rather being far richer (see " The Scala Type System "). Scala Type系统的主要优点不是更强大 ,而是更丰富 (参见“ Scala类型系统 ”)。
(Java can define some of them, and implement others, but Scala has them built-in). (Java可以定义其中的一些,并实现其他的,但Scala内置了它们)。
See also The Myth Makers 1: Scala's "Type Types" , commenting Steve Yegge's blog post , where he "disses" Scala as "Frankenstein's Monster" because "there are type types, and type type types". 另见神话制造者1:Scala的“类型类型” ,评论Steve Yegge的博客文章 ,他将“Scala”视为“Frankenstein's Monster”,因为“有类型类型和类型类型”。

The main safety problem with Java relates to variance. Java的主要安全问题与方差有关。 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. 基本上,程序员可以使用不正确的方差声明,这可能导致在Java中运行时抛出异常,而Scala不允许这样做。

In fact, the very fact that Java's Array is co-variant is already a problem, since it allows incorrect code to be generated. 事实上,Java的Array是共变体这一事实已经成为一个问题,因为它允许生成错误的代码。 For instance, as exemplified by sepp2k : 例如,如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. 然后,当然,Java中有原始类型,它允许所有类型的东西。

Also, though Scala has it as well, there's casting. 此外,虽然Scala也有它,但是有铸造。 Java API is rich in type casts, and there's no idiom like Scala's case x: X => // x is now safely cast . Java API具有丰富的类型转换,并且没有类似Scala的case x: X => // x is now safely cast Sure, one case use instanceof to accomplish that, but there's no incentive to do it. 当然,有一个案例使用instanceof来实现这一点,但没有动力去做。 In fact, Scala's asInstanceOf is intentionally verbose. 实际上,Scala的asInstanceOf是故意冗长的。

These are the things that make Scala's type system stronger. 这些是使Scala的类型系统更强大的东西。 It is also much richer, as VonC shows. 正如VonC所示,它也更加丰富。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM