Lists are not built in in Scala; they are defined by an abstract class List, which comes with two subclasses for :: and Nil. List 并不是Scala的内置类型。List被定义为抽象类。
1
2
package scala
abstract class List[+A] {
List is an abstract class, so one cannot define elements by calling the empty List constructor (e.g. by new List). The class has a type parameter a. It is co-variant in this parameter,which means thatList[S] <: List[T] for all types S and T such thatS <: T.The class is situated in the package scala.This is a package containing the most important standard classes of Scala. List defines a number of methods, which are explained in the following. List 是抽象类,所以没有办法通过空的List构造器来定义元素。List存在一个类型参数A。该参数是协变类型, 对于任意类型S和T,如果S<:T, 则 List[S]<:List[T]。该类的定义在scala package中。这个包是Scala中最重要的标准calsses。
Call-by-value has the advantage that it avoids repeated evaluation of arguments. Call-by-name has the advantage that it avoids evaluation of arguments when the parameter is not used at all by the function. Call-by-value is usually more efficient than call-by-name, but a call-by-value evaluation might loop where a call-by-name evaluation would terminate. Consider:
Then first(1, loop) reduces with call-by-name to 1, whereas the same term reduces with call-by-value repeatedly to itself, hence evaluation does not terminate. first(1, loop) → first(1, loop) → first(1, loop) → … 上面的例子,之所以不停的循环的原因就是,y 被声明为 Call-by-value,因而,按照上面的说法,无论是否这个参数会被用到,该参数都会被计算,所以会不停的循环。
Scala uses call-by-value by default, but it switches to call-by-name evaluation if the parameter type is preceded by =>.
1
2
3
4
5
scala> def constOne(x: Int, y: => Int) = 1
constOne: (Int,=> Int)Int
scala> constOne(1, loop)
unnamed0: Int = 1
scala> constOne(loop, 2) // gives an infinite loop.