简体   繁体   English

什么是Scala的“强大”类型系统?

[英]What is Scala's “powerful” type system?

When Scala is discussed, the type system is always mentioned as one of the primary features. 讨论Scala时,类型系统始终被视为主要功能之一。 It is referred to as powerful, and the primary reason for the language moniker (Scala being short for "scalable language"). 它被称为强大的,并且是语言名字对象的主要原因(Scala是“可伸缩语言”的缩写)。 Could someone please explain how Scala typing works/why this unique, and how that contributes to the language being scalable? 有人可以解释Scala键入的工作原理/为什么这个独特的,以及它如何有助于语言的可扩展性?

I don't think the existing answers are appropriate. 我不认为现有的答案是恰当的。 Scala has a lot of conveniences, but they are not related to the type system being powerful just because they relate to types. Scala有很多便利,但它们与类型系统无关,因为它们与类型有关。 In fact, type inference is in direct conflict with the power of the type system -- were it less powerful, one could have full type inference (like in Haskell). 事实上,类型推断与类型系统的力量直接冲突 - 如果它不那么强大,可以有完整的类型推断(如在Haskell中)。

So, 所以,

  • Scala has classes with members. Scala有成员的课程。 (Obvious, but I'm trying to be exhaustive here.) (很明显,但我想在这里详尽无遗。)
  • Method ("def") members of a scala class can have zero or more parameter lists, each of which can have zero or more parameters, the last of which might be a vararg. scala类的方法(“def”)成员可以具有零个或多个参数列表,每个参数列表可以具有零个或多个参数,最后一个参数可以是vararg。
  • Parameters may be passed by value or by name. 参数可以通过值或名称传递。
  • Parameters have names and may have default values. 参数具有名称,可能具有默认值。
  • Scala has "var" and "val" members (which are, in practice, also methods). Scala有“var”和“val”成员(实际上也是方法)。
  • Scala has "lazy val" members. 斯卡拉有“懒惰的”成员。
  • Scala has "type" members (type aliases), which may be specified as fixed types or as type boundaries. Scala具有“类型”成员(类型别名),可以指定为固定类型或类型边界。
  • Scala has abstract classes and members (all of the above members may be abstract). Scala有抽象类和成员(以上所有成员都可能是抽象的)。
  • Scala has inner class, traits and objects (Scala's inner class are different than Java's). Scala有内部类,特征和对象(Scala的内部类与Java不同)。
  • Scala's members, plus inner stuff, may be overriden. Scala的成员,加上内部的东西,可能会被覆盖。
  • Scala has type inheritance. Scala具有类型继承。
  • Scala has traits, providing multiple-inheritance with type linearization. Scala具有特征,提供类型线性化的多重继承。
  • Scala's traits's method members may have abstract override (stackable, aspect-like override). Scala的traits的方法成员可能具有抽象覆盖(可堆叠,类似方面的覆盖)。
  • Scala has singleton types. Scala有单例类型。
  • Scala has companion class/objects (related to scope). Scala具有伴随类/对象(与范围相关)。
  • Scala has private, protected and public scopes for classes, traits, singletons and members. Scala拥有私人,受保护和公共范围的课程,特征,单身人士和成员。
  • Scala's private and protected scopes can be limited to any enclosing package, class, trait or singleton, plus "this". Scala的私有和受保护范围可以限制为任何封闭的包,类,特征或单例,加上“this”。
  • Scala has self types. Scala有自我类型。
  • Scala has type parameters. Scala具有类型参数。
  • Scala's type parameters can be co- and contra-variant, as well as invariant. Scala的类型参数可以是共变量和反变量,也可以是不变量。
  • Scala has type constructors. Scala具有类型构造函数。
  • Scala has higher-order types. Scala具有更高阶的类型。
  • Scala has existential types. Scala具有存在类型。
  • Scala has structural types. Scala具有结构类型。
  • Scala has implicit parameters. Scala具有隐式参数。
  • Scala has function types, though, since they are simply a class plus syntactic sugar, I don't think it belongs on this list. Scala有函数类型,因为它们只是一个类加上语法糖,我不认为它属于这个列表。 On the other hand, function types are part of view bounds, so maybe it does. 另一方面,函数类型是视图边界的一部分,所以也许它可以。
  • Scala has a top (like almost everyone) and a bottom (like other statically typed fp languages). Scala有一个顶级(几乎每个人)和一个底部(像其他静态类型的fp语言)。
  • Scala's "unit" is a type with a value (as opposed to "void" elsewhere). Scala的“单位”是一种具有价值的类型(与其他地方的“无效”相对)。

Next, there are features related to Scala's implicits, which is what merit their inclusion above. 接下来,有一些与Scala的含义相关的功能,这是它们的优点。

  • Scala has view bounds, an implicit parameter that acts like another type bound. Scala具有视图边界,这是一个隐式参数,其作用类似于另一种类型绑定。
  • Scala has context counds, an implicit parameter that acts like another bound. Scala有上下文counds,一个隐含的参数,就像另一个绑定。
  • Generally speaking, implicit parameters and type inference can be combined to construct arbitrary complex proofs over the type parameters. 一般而言,可以组合隐式参数和类型推断以在类型参数上构造任意复杂证明。

Related to the last comment, implicits and type inference, together, make Scala's type system turing complete . 与上一个注释,implicits和类型推断相关联,使得Scala的类型系统turing完整 That is, you codify arbitrary programs as types, that will be "run" at compile time by the compiler. 也就是说,您将任意程序编码为类型,编译器将在编译时“运行”。 Proof here , by way of SKI Calculus, with a "buggy" infinite loop in the types as further demonstration. 这里证明,通过SKI微积分,在类型中有一个“越野车”无限循环作为进一步的演示。

The list of features above is quite big and impressive on many points. 上面的功能列表相当大,令人印象深刻。 It is, however, the way Scala combines implicits and type inference to produce static proofs at compile time (such as view bounds and context bounds) that make Scala's type system unique. 然而,Scala结合implicits和类型推断以在编译时生成静态证明(例如视图边界和上下文边界)的方式使得Scala的类型系统是唯一的。 AFAIK, there is no other language doing that, though there are certainly other languages providing proof capabilities through other means. AFAIK,没有其他语言可以做到这一点,尽管肯定有其他语言通过其他方式提供证明功能。

A few advantages of Scala's type system over Java's: Scala的类型系统优于Java的一些优点:

  1. Types can be inferred in many cases, instead of being specified explicitly. 在许多情况下可以推断出类型,而不是明确指定。 This is more of a convenience, but it promotes using complicated types. 这更方便,但它促进了使用复杂的类型。

    val map = new Map[String, (String, String)]()

    instead of 代替

    Map<String, Tuple<String, String>> map = new HashMap<String, Tuple<String, String>>()

  2. Functions can be expressed simply in the type system. 功能可以在类型系统中简单表达。 If you want to see how powerful this is, consider the guava library as a work-around for Java . 如果你想看看它有多强大,可以考虑将番石榴库作为Java的解决方案。 It's incredibly constrained and verbose (but still useful). 这是令人难以置信的约束和冗长(但仍然有用)。

    val double = (x: Int) => x * 2

    instead of (using Guava) 而不是(使用番石榴)

    Function<Integer, Integer> double = new Function<Integer, Integer>() { @Override public Integer apply(Integer value) { return value * 2; }}

  3. Tuples are a type in Scala, circumventing Java's problem of only being able to return a single value. 元组是Scala中的一种类型,它绕过了Java只能返回单个值的问题。

  4. Scala supports type Variances so you can specify that SomeObject is a subtype of SomeObject when Cat is a subtype of Thing (or when the reverse relation holds). Scala支持类型方差,因此当Cat是Thing的子类型时(或当反向关系成立时),您可以指定SomeObject是SomeObject的子类型。 In java, generics are not covariant , which is often problematic. 在java中, 泛型不是协变的 ,这通常是有问题的。

  5. Scala supports a limited form of multiple-inheritence using traits . Scala使用特征支持有限形式的多重继承。 Unlike interfaces (of which multiple can be implemented in Java), traits can define methods and variables. 与接口(其中多个可以用Java实现)不同,特征可以定义方法和变量。

  6. Arrays are transparently handled like any other class. 数组像任何其他类一样透明地处理。

  7. You can add methods to existing classes through implicit definitions. 您可以通过隐式定义向现有类添加方法 For example, you could add a "sum" method to Arrays of Integers. 例如,您可以向Arrays of Integers添加“sum”方法。

     class IntArray(value: Array[Int]) { def sumIt = value.reduceRight(_+_) } implicit def pimpArray(xs: Array[Int]) = new IntArray(xs) Array(1,2,3).sumIt 

This is another good resource for some of the above topics: http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5 对于上述某些主题,这是另一个很好的资源: http//www.codecommit.com/blog/scala/scala-for-java-refugees-part-5

In addition to schmmd's excellent answer, Scala's type system has even more important features: 除了schmmd的优秀答案,Scala的类型系统还有更重要的功能:

  • object s are a clean alternative to static member variables and methods in Java, eg an object has it's own type and can be passed as argument object是Java中static成员变量和方法的干净替代,例如, object具有自己的类型,可以作为参数传递
  • type declarations: you can define aliases for complicated types, like type FactorMap[A] = Map[A, Set[Int]] type声明:您可以为复杂类型定义别名,例如type FactorMap[A] = Map[A, Set[Int]]
  • abstract type members as alternative to generic-style types 抽象类型成员作为泛型样式的替代
  • self types 自我类型
  • structural types 结构类型
  • multiple argument lists for currying currying的多个参数列表
  • implicit parameters and conversions, together with view bounds. 隐式参数和转换,以及视图边界。 This leads to the "pimp my library" pattern and can be used to simulate Haskell-style typeclasses 这导致了“pimp my library”模式,可以用来模拟Haskell风格的类型类
  • higher order types 高阶类型

The last point is one of my favorites. 最后一点是我的最爱之一。 Eg you can't write a simple general functor interface in Java. 例如,你不能用Java编写简单的通用仿函数接口。 You would need ... 需要 ......

public interface Function<A,B> {
   public B apply(A a);
}

//not valid Java
public interface Functor<C> {
   public <A,B> C<B> map(Function<A,B> fn, C<A> ca);
}

It works if you substitute some concrete type like List instead of C . 如果你替换像List而不是C这样的具体类型,它就可以工作。 In Java you can abstract over the content of a containter (eg by writing `List), but you can't abstract over the container itself . 在Java中,您可以抽象出一个包含的内容(例如,通过编写`List),但是您不能在容器本身上进行抽象。 Trust me, I tried to find loopholes (the result was this ). 相信我,我试图找到漏洞(结果就是这个 )。 In Scala it's a breeze: 在Scala中,这是一件轻而易举的事:

trait Functor[C[_]] {
   def map[A,B](fn: A => B, ca: C[A]):C[B]
}

object ListFunctor extends Functor[List] {
   def map[A,B](fn: A => B, ca: List[A]):List[B] = ca.map(fn)
}

Any type system in which you can encode HList, TList and HOF for types is quite powerful IMHO. 任何类型系统,你可以编码HList,TList和HOF的类型是相当强大的恕我直言。 See http://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala/ for more information. 有关详细信息,请参阅http://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala/

I don't know if you know Java, but imagine Scala's type system like this: 我不知道你是否了解Java,但想象Scala的类型系统是这样的:

  • Remove Java's artificial limitations of what you can do with types and generics 删除Java对类型和泛型所能做的人为限制
  • Add the common features of functional languages to it 添加函数式语言的常用功能
  • Innovate on the oop/inheritance front 创新oop /继承前沿

i would love o wrie more, bu my keyboard jus broke, sorry! 我会更喜欢o wrie,我的键盘jus坏了,对不起!

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

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