Spec2.8ChapBa

Chapter B 変更履歴



バージョン 2.8.0 中の変更

お終いのカンマ (Trailing commas) 式、引数、型あるいはパターンシーケンス中のお終いのカンマは、 もうサポートされません。



バージョン 2.8 中の変更(開発中)

Changed visibility rules for nested packages (where done?) Changed visibility rules in §2 so that packages are no longer treated specially .

ネストしたパッケージの可視性規則を変更(どこでした?)

§2 中の可視性規則を、パッケージが特別扱いされないように変更した。

Added section §3.5.3 on weak conformance . Relaxed type rules for conditionals, match expressions, try expressions to compute their result type using least upper bound wrt weak conformance . Relaxed type rule for local type inference so that argument types need only weekly conform to inferred formal parameter types . Added section on numeric widening in §6.26 to support weak conformance .

§3.5.3 に弱い適合性に関する節を追加。 最少の上限境界を使って結果型を計算するために、条件、マッチ式、try 式の型規則を 緩めた。 引数型が、推論された形式上のパラメータ型に弱く適合することだけが 必要であるように、ローカルな型推論に対する型規則を緩めた。 弱適合性をサポートするために、§6.26 中に数値拡張に関する節を追加。

Tightened rules to avpod accidential overrides in §5.1.4 . Removed class literals . Added section §7.4 on context bounds . Clarified differences between isInstanceOf and pattern matches (§12.1) . Allowed implicit modifier on function literals with a single parameter (§6.23) .

§5.1.4 中の想定外のオーバライドを避けるために規則を強化。

クラスリテラル削除。

コンテキスト境界に関する節を §7.4 に追加。

isInstanceOf とパターンマッチの相違を明確化(§12.1)。

ただ 1 つのパラメータをもつ関数リテラルに対する implicit 修飾子を許可(§6.23)。

(訳注:------- これより以前の履歴は、見出し、体裁以外は原文のままです ------ )



バージョン 2.7.2 (2008-11-10) 中の変更


代入演算子の優先順位

The precedence of assignment operators has been brought in line with Java's (§6.12). From now on, += has the same precedence as =.


関数パラメータとしてのワイルドカード

A formal parameter to an anonymous fucntion may now be a wildcard represented by an underscore (§6.23). Example:

   _ => 7   // The function that ignores its argument
            // and always returns 7.


左矢印のユニコード代替物

The Unicode glyph \u2190 '←' is now treated as a reserved identifier, equivalent to the ASCII symbol '<-'.



バージョン 2.7.1 (2008-4-09) 中の変更

型におけるワイルドカードプレースホルダに関するスコープ規則変更

A wildcard in a type now binds to the closest enclosing type application. For example List[List[_]] is now equivalent to the existential type

   List[List[t] forSome { type t }] .

In version 2.7.0, the type expanded instead to

   List[List[t]] forSome { type t } .

The new convention corresponds exactly to the way wildcards in Java are interpreted .


No Contractiveness Requirement for Implicits

The contractiveness requirement for implicit method definitions has been dropped. Instead it is checked for each implicit expansion individually that the expansion does not result in a cycle or a tree of infinitely growing types (§7.2).



バージョン 2.7.0 (2008-2-07) 中の変更


Java ジェネリック(総称型)

Scala now supports Java generic types by default:

  • A generic type in Java such as ArrayList<String> is translated to a generic type in Scala: ArrayList[String].
  • A wildcard type such as ArrayList<? extends Number> is translated to ArrayList[_ <: Number]. This is itself a shorthand for the existential type ArrayList[T] forSome { type T <: Number }.
  • A raw type in Java such as ArrayList is translated to ArrayList[_], which is a shorthand for ArrayList[T] forSome { type T }.

This translation works if -target:jvm-1.5 is specified, which is the new default. For any other target, Java generics are not recognized. To ensure upgradability of Scala codebases, extraneous type parameters for Java classes under -target:jvm-1.4 are simply ignored. For instance, when compiling with -target:jvm-1.4, a Scala type such as ArrayList[String] is simply treated as the unparameterized type ArrayList.


ケースクラスへの変更

The Scala compiler generates now for every case class a companion extractor object (§5.3.2). For instance, given the case class:

   case class X(elem: String)

the following companion object is generated:

   object X {
     def unapply(x: X): Some[String] = Some(x.elem)
     def apply(s: String): X = new X(s)
   }

If the object exists already, only the apply and unapply methods are added to it. Three restrictions on case classes have been removed.

  1. Case classes can now inherit from other case classes.
  2. Case classes may now be abstract.
  3. Case classes may now come with companion objects.



バージョン 2.6.1 (2007-11-30) 中の変更

パターン束縛によるミュータブル変数の導入

Mutable variables can now be introduced by a pattern matching definition (§4.2), just like values can. Examples:

   var (x, y) = if (positive) (1, 2) else (-1, -3)
   var hd :: tl = mylist


自己型(Self-types)

Self types can now be introduced without defining an alias name for this (§5.1). Example:

   class C {
     type T <: Trait
     trait Trait { this: T => ... }
   }



バージョン 2.6 (2007-7-27) 中の変更

存在型(Existential types)

It is now possible to define existential types (§3.2.10). An existential type has the form T forSome {Q} where Q is a sequence of value and/or type declarations. Given the class definitions

   class Ref[T]
   abstract class Outer { type T }

one may for example write the following existential types

   Ref[T] forSome { type T <: java.lang.Number }
   Ref[x.T] forSome { val x: Outer }


遅延評価Val(Lazy values)

It is now possible to define lazy value declarations using the new modifier lazy (§4.1). A lazy value definition evaluates its right hand side e the first time the value is accessed. Example:

   import compat.Platform._
   val t0 = currentTime
   lazy val t1 = currentTime
   
   val t2 = currentTime
   
   println("t0 <= t2: " + (t0 <= t2))        //true
   println("t1 <= t2: " + (t1 <= t2))        //false (lazy evaluation of t1)


構造的型(Structural types)

It is now possible to declare structural types using type refinements (§3.2.7). For example:

   class File(name: String) {
     def getName(): String = name
     def open() { /*..*/ }
     def close() { println("close file") }
   }
   def test(f: { def getName(): String }) { println(f.getName) }
   
   test(new File("test.txt"))
   test(new java.io.File("test.txt"))

There's also a shorthand form for creating values of structural types. For instance,

   new { def getName() = "aaron" }

is a shorthand for

 new AnyRef{ def getName() = "aaron" }



バージョン 2.5 (2007-5-02) 中の変更


型コンストラクタの多相性(Type constructor polymorphism (*1))

Type parameters (§4.4) and abstract type members (§4.3) can now also abstract over type constructors (§3.3.3). This allows a more precise Iterable interface:

 trait Iterable[+T] {
   type MyType[+T] <: Iterable[T] // MyType is a type constructor
 
      def filter(p: T => Boolean): MyType[T] = ...
      def map[S](f: T => S): MyType[S] = ...
 }

(*1) Implemented by Adriaan Moors

 abstract class List[+T] extends Iterable[T] {
   type MyType[+T] = List[T]
 }

This definition of Iterable makes explicit that mapping a function over a certain structure (e.g., a List) will yield the same structure (containing different elements).


オブジェクトの事前初期化(Early object initialization)

It is now possible to initialize some fields of an object before any parent constructors are called (§5.1.6). This is particularly useful for traits, which do not have normal constructor parameters. Example:

 trait Greeting {
   val name: String
   val msg = "How are you, "+name
 }
 class C extends {
   val name = "Bob"
 } with Greeting {
   println(msg)
 }

In the code above, the field name is initialized before the constructor of Greeting is called. Therefore, field msg in class Greeting is properly initialized to "How are you, Bob".


For内包表記、再掲

The syntax of for-comprehensions has changed (§6.19). In the new syntax, generators do not start with a val anymore, but filters start with an if (and are called guards). A semicolon in front of a guard is optional. For example:

 for (val x <- List(1, 2, 3); x % 2 == 0) println(x)

is now written

 for (x <- List(1, 2, 3) if x % 2 == 0) println(x)

The old syntax is still available but will be deprecated in the future.


暗黙の無名関数(Implicit anonymous functions)

It is now possible to define anonymous functions using underscores in parameter position (§Example 6.23.1). For instance, the expressions in the left column are each function values which expand to the anonymous functions on their right.

 _ + 1                              x => x + 1
 _ * _                              (x1, x2) => x1 * x2
 (_: int) * 2                       (x: int) => (x: int) * 2
 if (_) x else y                    z => if (z) x else y
 _.map(f)                           x => x.map(f)
 _.map(_ + 1)                       x => x.map(y => y + 1)

As a special case (§6.7), a partially unapplied method is now designated m _ instead of the previous notation &m. The new notation will displace the special syntax forms .m() for abstracting over method receivers and &m for treating an unapplied method as a function value. For the time being, the old syntax forms are still available, but they will be deprecated in the future.


パターンマッチング無名関数、再掲

It is now possible to use case clauses to define a function value directly for functions of arities greater than one (§8.5). Previously, only unary functions could be defined that way. Example:

 def scalarProduct(xs: Array[Double], ys: Array[Double]) =
   (0.0 /: (xs zip ys)) {
     case (a, (b, c)) => a + b * c
   }



バージョン 2.4 (2007-3-09) 中の変更

オブジェクトローカルな private と protected (Object-local private and protected)

The private and protected modifiers now accept a [this] qualifier (§5.2). A definition M which is labelled private[this] is private, and in addition can be accessed only from within the current object. That is, the only legal prefixes for M are this or C.this. Analogously, a definition M which is labelled protected[this] is protected , and in addition can be accessed only from within the current object.


タプル、再掲

The syntax for tuples has been changed from {...} to (...) (§6.9). For any sequence of types T1,...,Tn , (T1,...,Tn) is a shorthand for Tuplen[T1,...,Tn].

Analogously, for any sequence of expressions or patterns x1,...,xn , (x1,...,xn) is a shorthand for Tuplen(x1,...,xn).


基本コンストラクタへのアクセス修飾子

The primary constructor of a class can now be marked private or protected (§5.3). If such an access modifier is given, it comes between the name of the class and its value parameters. Example:

 class C[T] private (x: T) { ... }


アノテーション(Annotations)

The support for attributes has been extended and its syntax changed (§11). Attributes are now called annotations. The syntax has been changed to follow Java's conventions, e.g. @attribute instead of [attribute]. The old syntax is still available but will be deprecated in the future. Annotations are now serialized so that they can be read by compile-time or runtime

tools. Class scala.Annotation has two sub-traits which are used to indicate how annotations are retained. Instances of an annotation class inheriting from trait scala.ClassfileAnnotation will be stored in the generated class files. Instances of an annotation class inheriting from trait scala.StaticAnnotation will be visible to the Scala type-checker in every compilation unit where the annotated symbol is accessed.

決定可能なサブ型付け(Decidable subtyping)

The implementation of subtyping has been changed to prevent infinite recursions. Termination of subtyping is now ensured by a new restriction of class graphs to be finitary (§5.1.5).

ケースクラスは抽象ではない(Case classes cannot be abstract)

It is now explicitly ruled out that case classes can be abstract (§5.2). The specification was silent on this point before, but did not explain how abstract case classes were treated. The Scala compiler allowed the idiom.

自己エイリアス、自己型に対する新文法

It is now possible to give an explicit alias name and/or type for the self reference this (§5.1). For instance, in

 class C { self: D =>
   ...
 }

the name self is introduced as an alias for this within C and the self type (§5.3) of C is assumed to be D. This construct is introduced now in order to replace eventually both the qualified this construct C.this and the requires clause in Scala.


代入演算子

It is now possible to combine operators with assignments (§6.12.4). Example:

 var x: int = 0
 x += 1



バージョン 2.3.2 (2007-1-23) 中の変更

抽出子(Extractors)

It is now possible to define patterns independently of case classes, using unapply methods in extractor objects (§8.1.8). Here is an example:

 object Twice {
   def apply(x:Int): int = x*2
   def unapply(z:Int): Option[int] = if (z%2==0) Some(z/2) else None
 }
 val x = Twice(21)
 x match { case Twice(n) => Console.println(n) } // prints 21

In the example, Twice is an extractor object with two methods:

  • The apply method is used to build even numbers.
  • The unapply method is used to decompose an even number; it is in a sense the reverse of apply. unapply methods return option types: Some(...) for a match that suceeds, None for a match that fails. Pattern variables are returned as the elements of Some. If there are several variables, they are grouped in a tuple.

In the second-to-last line, Twice's apply method is used to construct a number x. In the last line, x is tested against the pattern Twice(n). This pattern succeeds for even numbers and assigns to the variable n one half of the number that was tested. The pattern match makes use of the unapply method of object Twice. More details on extractors can be found in the paper "Matching Objects with Patterns" by Emir, Odersky and Williams.


タプル(Tuples)

A new lightweight syntax for tuples has been introduced (§6.9). For any sequence of types T1,...,Tn , {T1,...,Tn} is a shorthand for Tuplen[T1,...,Tn].

Analogously, for any sequence of expressions or patterns x1,...,xn , {x1,...,xn} is a shorthand for Tuplen(x1,...,xn).


多項の中置演算子(Infix operators of greater arities)

It is now possible to use methods which have more than one parameter as infix operators (§6.12). In this case, all method arguments are written as a normal parameter list in parentheses. Example:

 class C {
   def +(x: int, y: String) = ...
 }
 val c = new C
 c + (1, "abc")


廃棄属性(Deprecated attribute)

A new standard attribute deprecated is available (§11). If a member definition is marked with this attribute, any reference to the member will cause a "deprecated" warning message to be emitted.



バージョン 2.3 (2006-11-23) 中の変更


手続き(Procedures)

A simplified syntax for functions returning unit has been introduced (§4.6.3). Scala now allows the following shorthands:

   def f(params)              for        def f(params): unit
   def f(params) { ... }      for        def f(params): unit = { ... }


型パターン(Type Patterns)

The syntax of types in patterns has been refined (§8.2). Scala now distinguishes between

type variables (starting with a lower case letter) and types as type arguments

in patterns. Type variables are bound in the pattern. Other type arguments are, as in previous versions, erased. The Scala compiler will now issue an "unchecked" warning at places where type erasure might compromise type-safety.


標準の型(Standard Types)

The recommended names for the two bottom classes in Scala's type hierarchy have changed as follows:

 All        ==>       Nothing
 AllRef     ==>       Null

The old names are still available as type aliases.



バージョン 2.1.8 (2006-8-23) 中の変更

protectedに対する可視修飾子(Visibility Qualifier for protected)

Protected members can now have a visibility qualifier (§5.2), e.g. protected[<qualifier>]. In particular, one can now simulate package protected access as in Java writing

   protected[P] def X ...

where P would name the package containing X.


privateアクセスの緩和(Relaxation of Private Acess)

Private members of a class can now be referenced from the companion module of the class and vice versa (§5.2)


暗黙の検索(Implicit Lookup)

The lookup method for implicit definitions has been generalized (§7.2). When searching for an implicit definition matching a type T , now are considered

  1. all identifiers accessible without prefix, and
  2. all members of companion modules of classes associated with T .

(The second clause is more general than before). Here, a class is associated with a type T if it is referenced by some part of T , or if it is a base class of some part of T . For instance, to find implicit members corresponding to the type

   HashSet[List[Int], String]

one would now look in the companion modules (aka static parts) of HashSet, List, Int, and String. Before, it was just the static part of HashSet.


厳しくなったパターンマッチ(Tightened Pattern Match)

A typed pattern match with a singleton type p.type now tests whether the selector value is reference-equal to p (§8.1). Example:

     val p = List(1, 2, 3)
     val q = List(1, 2)
     val r = q
     r match {
       case _: p.type => Console.println("p")
       case _: q.type => Console.println("q")
     }

This will match the second case and hence will print "q". Before, the singleton types were erased to List, and therefore the first case would have matched, which is nonsensical .



バージョン 2.1.7 (2006-7-19) 中の変更

複数行文字列リテラル(Multi-Line string literals)

It is now possible to write multi-line string-literals enclosed in triple quotes (§1.3.5). Example:

 """this is a
    multi-line
    string literal"""

No escape substitutions except for unicode escapes are performed in such string literals.


クロージャ構文(Closure Syntax)

The syntax of closures has been slightly restricted (§6.23). The form

     x: T => E

is valid only when enclosed in braces, i.e. { x: T => E }. The following is illegal, because it might be read as the value x typed with the type T => E:

     val f = x: T => E

Legal alternatives are:

     val f = { x: T => E }
     val f = (x: T) => E



バージョン 2.1.5 (2006-5-24) 中の変更


クラスリテラル(Class Literals)

There is a new syntax for class literals (§6.2): For any class type C , classOf[C] designates the run-time representation of C .



バージョン 2.0 (2006-3-12) 中の変更

Scala in its second version is different in some details from the first version of the language. There have been several additions and some old idioms are no longer supported. This appendix summarizes the main changes.

新しいキーワード(New Keywords)

The following three words are now reserved; they cannot be used as identifiers (§1.1)

 implicit       match       requires


文区切りとしての改行(Newlines as Statement Separators)

Newlines can now be used as statement separators in place of semicolons (§1.2)


構文の制限(Syntax Restrictions)

There are some other situations where old constructs no longer work:

Pattern matching expressions. The match keyword now appears only as infix operator between a selector expression and a number of cases, as in:

   expr match {
     case Some(x) => ...
     case None => ...
   }

Variants such as expr.match {...} or just match {...} are no longer supported .

"With" in extends clauses. . The idiom

 class C with M { ... }

is no longer supported. A with connective is only allowed following an extends clause. For instance, the line above would have to be written

 class C extends AnyRef with M { ... } 

However, assuming M is a trait (see 5.3.3), it is also legal to write

 class C extends M { ... }

The latter expression is treated as equivalent to

 class C extends S with M { ... }

where S is the superclass of M.

Regular Expression Patterns. The only form of regular expression pattern that is currently supported is a sequence pattern, which might end in a sequence wildcard _*. Example:

 case List(1, 2, _*) => ... // will match all lists starting with \code{1,2}.

It is at current not clear whether this is a permanent restriction. We are evaluating the possibility of re-introducing full regular expression patterns in Scala.


自己型アノテーション(Selftype Annotations)

The recommended syntax of selftype annotations has changed.

 class C: T extends B { ... }

becomes

 class C requires T extends B { ... }

That is, selftypes are now indicated by the new requires keyword. The old syntax is still available but is considered deprecated.


For内包表記(For-comprehensions)

For-comprehensions (§6.19) now admit value and pattern definitions. Example:

 for {
   val x <- List.range(1, 100)
   val y <- List.range(1, x)
   val z = x + y
   isPrime(z)
 } yield Pair(x, y)

Note the definition val z = x + y as the third item in the for-comprehension.


変換(Conversions)

The rules for implicit conversions of methods to functions (§6.26) have been tightened . Previously, a parameterized method used as a value was always implicitly converted to a function. This could lead to unexpected results when method arguments where forgotten. Consider for instance the statement below:

 show(x.toString)

where show is defined as follows:

 def show(x: String) = Console.println(x) .

Most likely, the programmer forgot to supply an empty argument list () to toString. The previous Scala version would treat this code as a partially applied method, and expand it to:

 show(() => x.toString())

As a result, the address of a closure would be printed instead of the value of s. Scala version 2.0 will apply a conversion from partially applied method to function value only if the expected type of the expression is indeed a function type. For instance , the conversion would not be applied in the code above because the expected type of show's parameter is String, not a function type. The new convention disallows some previously legal code. Example:

 def sum(f: int => double)(a: int, b: int): double =
   if (a > b) 0 else f(a) + sum(f)(a + 1, b)
 
 val sumInts    =   sum(x => x)    // error: missing arguments

The partial application of sum in the last line of the code above will not be converted to a function type. Instead, the compiler will produce an error message which states that arguments for method sum are missing. The problem can be fixed by providing an expected type for the partial application, for instance by annotating the definition of sumInts with its type:

 val sumInts: (int, int) => double        =   sum(x => x)    // OK

On the other hand, Scala version 2.0 now automatically applies methods with empty parameter lists to () argument lists when necessary. For instance, the show expression above will now be expanded to

 show(x.toString()) .

Scala version 2.0 also relaxes the rules of overriding with respect to empty parameter lists. The revised definition of matching members (§5.1.3) makes it now possible to override a method with an explicit, but empty parameter list () with a parameterless method, and vice versa. For instance, the following class definition is now legal:

 class C {
   override def toString: String = ...
 }

Previously this definition would have been rejected, because the toString method as inherited from java.lang.Object takes an empty parameter list.


クラスパラメータ(Class Parameters)

A class parameter may now be prefixed by val or var (§5.3).


private修飾子(Private Qualifiers)

Previously, Scala had three levels of visibility: private, protected and public. There was no way to restrict accesses to members of the current package, as in Java. Scala 2 now defines access qualifiers that let one express this level of visibility, among others. In the definition

 private[C] def f(...)

access to f is restricted to all code within the class or package C (which must contain the definition of f) (§5.2)


ミックスインモデルにおける変更

The model which details mixin composition of classes has changed significantly. The main differences are:

  1. We now distinguish between traits that are used as mixin classes and normal classes. The syntax of traits has been generalized from version 1.0, in that traits are now allowed to have mutable fields. However, as in version 1.0, traits still may not have constructor parameters.
  2. Member resolution and super accesses are now both defined in terms of a class linearization.
  3. Scala's notion of method overloading has been generalized; in particular, it is now possible to have overloaded variants of the same method in a subclass and in a superclass, or in several different mixins. This makes method overloading in Scala conceptually the same as in Java.

The new mixin model is explained in more detail in §5.


暗黙のパラメータ(Implicit Parameters)

Views in Scala 1.0 have been replaced by the more general concept of implicit parameters (§7)


パターンマッチングの柔軟な型付け

The new version of Scala implements more flexible typing rules when it comes to pattern matching over heterogeneous class hierarchies (§8.4). A heterogeneous class hierarchy is one where subclasses inherit a common superclass with different parameter types. With the new rules in Scala version 2.0 one can perform pattern matches over such hierarchies with more precise typings that keep track of the information gained by comparing the types of a selector and a matching pattern (§Example 8.4.1). This gives Scala capabilities analogous to guarded algebraic data types.

タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

最終更新:2011年02月23日 18:43
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。