diff --git a/_ba/tour/annotations.md b/_ba/tour/annotations.md index d39d970873..cccac64c35 100644 --- a/_ba/tour/annotations.md +++ b/_ba/tour/annotations.md @@ -5,7 +5,7 @@ language: ba partof: scala-tour num: 32 -next-page: default-parameter-values +next-page: packages-and-imports previous-page: by-name-parameters --- diff --git a/_config.yml b/_config.yml index 6ab7b65d5c..c5df7d0779 100644 --- a/_config.yml +++ b/_config.yml @@ -15,7 +15,7 @@ keywords: - Document - Guide -scala-version: 2.13.3 +scala-version: 2.13.4 scala-212-version: 2.12.12 collections: diff --git a/_data/translations.yml b/_data/translations.yml index 56d0fd59cf..80ab5afc1c 100644 --- a/_data/translations.yml +++ b/_data/translations.yml @@ -1,2 +1,2 @@ tour: - languages: [ba, es, ko, pt-br, pl, zh-cn, th, ru, ja] + languages: [ba, es, fr, ko, pt-br, pl, zh-cn, th, ru, ja] diff --git a/_es/tour/annotations.md b/_es/tour/annotations.md index c49cbe3e8c..37dd912f97 100644 --- a/_es/tour/annotations.md +++ b/_es/tour/annotations.md @@ -6,7 +6,7 @@ partof: scala-tour num: 3 language: es -next-page: classes +next-page: packages-and-imports previous-page: abstract-type-members --- diff --git a/_fr/tour/abstract-type-members.md b/_fr/tour/abstract-type-members.md new file mode 100644 index 0000000000..1239bebfd6 --- /dev/null +++ b/_fr/tour/abstract-type-members.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Abstract Type Members +partof: scala-tour + +num: 21 + +language: fr + +next-page: compound-types +previous-page: inner-classes +--- diff --git a/_fr/tour/annotations.md b/_fr/tour/annotations.md new file mode 100644 index 0000000000..5f2b4cbf55 --- /dev/null +++ b/_fr/tour/annotations.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Annotations +partof: scala-tour + +num: 30 + +language: fr + +next-page: packages-and-imports +previous-page: by-name-parameters +--- diff --git a/_fr/tour/automatic-closures.md b/_fr/tour/automatic-closures.md new file mode 100644 index 0000000000..f5a06a5f5f --- /dev/null +++ b/_fr/tour/automatic-closures.md @@ -0,0 +1,7 @@ +--- +layout: tour +title: Automatic Closures +partof: scala-tour + +language: fr +--- diff --git a/_fr/tour/basics.md b/_fr/tour/basics.md new file mode 100644 index 0000000000..d30be44941 --- /dev/null +++ b/_fr/tour/basics.md @@ -0,0 +1,11 @@ +--- +layout: tour +title: Basics +partof: scala-tour + +num: 2 +language: fr + +next-page: unified-types +previous-page: tour-of-scala +--- \ No newline at end of file diff --git a/_fr/tour/by-name-parameters.md b/_fr/tour/by-name-parameters.md new file mode 100644 index 0000000000..917e78aede --- /dev/null +++ b/_fr/tour/by-name-parameters.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: By-name Parameters +partof: scala-tour + +num: 29 + +language: fr + +next-page: annotations +previous-page: operators +--- diff --git a/_fr/tour/case-classes.md b/_fr/tour/case-classes.md new file mode 100644 index 0000000000..d5395721ea --- /dev/null +++ b/_fr/tour/case-classes.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Case Classes +partof: scala-tour + +num: 10 + +language: fr + +next-page: pattern-matching +previous-page: multiple-parameter-lists +--- diff --git a/_fr/tour/classes.md b/_fr/tour/classes.md new file mode 100644 index 0000000000..63480c2848 --- /dev/null +++ b/_fr/tour/classes.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Classes +partof: scala-tour + +num: 4 + +language: fr + +next-page: traits +previous-page: unified-types +--- \ No newline at end of file diff --git a/_fr/tour/compound-types.md b/_fr/tour/compound-types.md new file mode 100644 index 0000000000..db813518b1 --- /dev/null +++ b/_fr/tour/compound-types.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Compound Types +partof: scala-tour + +num: 22 + +language: fr + +next-page: self-types +previous-page: abstract-type-members +--- diff --git a/_fr/tour/default-parameter-values.md b/_fr/tour/default-parameter-values.md new file mode 100644 index 0000000000..0f73ab1653 --- /dev/null +++ b/_fr/tour/default-parameter-values.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Default Parameter Values +partof: scala-tour + +num: 31 + +language: fr + +next-page: named-arguments +previous-page: annotations +--- diff --git a/_fr/tour/extractor-objects.md b/_fr/tour/extractor-objects.md new file mode 100644 index 0000000000..ac5c1dc013 --- /dev/null +++ b/_fr/tour/extractor-objects.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Extractor Objects +partof: scala-tour + +num: 14 + +language: fr + +next-page: generic-classes +previous-page: regular-expression-patterns +--- diff --git a/_fr/tour/for-comprehensions.md b/_fr/tour/for-comprehensions.md new file mode 100644 index 0000000000..ea4649ad39 --- /dev/null +++ b/_fr/tour/for-comprehensions.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: For Comprehensions +partof: scala-tour + +num: 15 + +language: fr + +next-page: generic-classes +previous-page: extractor-objects +--- diff --git a/_fr/tour/generic-classes.md b/_fr/tour/generic-classes.md new file mode 100644 index 0000000000..6eeb2e8fea --- /dev/null +++ b/_fr/tour/generic-classes.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Generic Classes +partof: scala-tour + +num: 16 + +language: fr + +next-page: variances +previous-page: extractor-objects +--- diff --git a/_fr/tour/higher-order-functions.md b/_fr/tour/higher-order-functions.md new file mode 100644 index 0000000000..a26e90f16f --- /dev/null +++ b/_fr/tour/higher-order-functions.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Higher-order Functions +partof: scala-tour + +num: 7 + +language: fr + +next-page: nested-functions +previous-page: mixin-class-composition +--- diff --git a/_fr/tour/implicit-conversions.md b/_fr/tour/implicit-conversions.md new file mode 100644 index 0000000000..1030827e4b --- /dev/null +++ b/_fr/tour/implicit-conversions.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Implicit Conversions +partof: scala-tour + +num: 25 + +language: fr + +next-page: polymorphic-methods +previous-page: implicit-parameters +--- diff --git a/_fr/tour/implicit-parameters.md b/_fr/tour/implicit-parameters.md new file mode 100644 index 0000000000..236dd136f5 --- /dev/null +++ b/_fr/tour/implicit-parameters.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Implicit Parameters +partof: scala-tour + +num: 24 + +language: fr + +next-page: implicit-conversions +previous-page: self-types +--- diff --git a/_fr/tour/inner-classes.md b/_fr/tour/inner-classes.md new file mode 100644 index 0000000000..a5df305ce5 --- /dev/null +++ b/_fr/tour/inner-classes.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Inner Classes +partof: scala-tour + +num: 20 + +language: fr + +next-page: abstract-type-members +previous-page: lower-type-bounds +--- diff --git a/_fr/tour/lower-type-bounds.md b/_fr/tour/lower-type-bounds.md new file mode 100644 index 0000000000..eb6ffb785c --- /dev/null +++ b/_fr/tour/lower-type-bounds.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Lower Type Bounds +partof: scala-tour + +num: 19 + +language: fr + +next-page: inner-classes +previous-page: upper-type-bounds +--- diff --git a/_fr/tour/mixin-class-composition.md b/_fr/tour/mixin-class-composition.md new file mode 100644 index 0000000000..8d1b823c11 --- /dev/null +++ b/_fr/tour/mixin-class-composition.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Class Composition with Mixins +partof: scala-tour + +num: 6 + +language: fr + +next-page: higher-order-functions +previous-page: tuples +--- diff --git a/_fr/tour/multiple-parameter-lists.md b/_fr/tour/multiple-parameter-lists.md new file mode 100644 index 0000000000..476e918cc1 --- /dev/null +++ b/_fr/tour/multiple-parameter-lists.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Multiple Parameter Lists (Currying) +partof: scala-tour + +num: 9 + +language: fr + +next-page: case-classes +previous-page: nested-functions +--- diff --git a/_fr/tour/named-arguments.md b/_fr/tour/named-arguments.md new file mode 100644 index 0000000000..d9aba0c1c6 --- /dev/null +++ b/_fr/tour/named-arguments.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Named Arguments +partof: scala-tour + +num: 32 + +language: fr + +next-page: packages-and-imports +previous-page: default-parameter-values +--- diff --git a/_fr/tour/nested-functions.md b/_fr/tour/nested-functions.md new file mode 100644 index 0000000000..f92045364f --- /dev/null +++ b/_fr/tour/nested-functions.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Nested Methods +partof: scala-tour + +num: 8 + +language: fr + +next-page: multiple-parameter-lists +previous-page: higher-order-functions +--- diff --git a/_fr/tour/operators.md b/_fr/tour/operators.md new file mode 100644 index 0000000000..59c697727e --- /dev/null +++ b/_fr/tour/operators.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Operators +partof: scala-tour + +num: 28 + +language: fr + +next-page: by-name-parameters +previous-page: type-inference +--- diff --git a/_fr/tour/package-objects.md b/_fr/tour/package-objects.md new file mode 100644 index 0000000000..9c1b78716d --- /dev/null +++ b/_fr/tour/package-objects.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: Package Objects +language: fr +partof: scala-tour + +num: 36 +previous-page: packages-and-imports +--- \ No newline at end of file diff --git a/_fr/tour/packages-and-imports.md b/_fr/tour/packages-and-imports.md new file mode 100644 index 0000000000..8edac3b01c --- /dev/null +++ b/_fr/tour/packages-and-imports.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Packages and Imports +partof: scala-tour + +num: 33 + +language: fr + +previous-page: named-arguments +next-page: package-objects +--- diff --git a/_fr/tour/pattern-matching.md b/_fr/tour/pattern-matching.md new file mode 100644 index 0000000000..1cd3731b9a --- /dev/null +++ b/_fr/tour/pattern-matching.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Pattern Matching +partof: scala-tour + +num: 11 + +language: fr + +next-page: singleton-objects +previous-page: case-classes +--- diff --git a/_fr/tour/polymorphic-methods.md b/_fr/tour/polymorphic-methods.md new file mode 100644 index 0000000000..6375d54957 --- /dev/null +++ b/_fr/tour/polymorphic-methods.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Polymorphic Methods +partof: scala-tour + +num: 26 + +language: fr + +next-page: type-inference +previous-page: implicit-conversions +--- diff --git a/_fr/tour/regular-expression-patterns.md b/_fr/tour/regular-expression-patterns.md new file mode 100644 index 0000000000..c8f05a2c4b --- /dev/null +++ b/_fr/tour/regular-expression-patterns.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Regular Expression Patterns +partof: scala-tour + +num: 13 + +language: fr + +next-page: extractor-objects +previous-page: singleton-objects +--- diff --git a/_fr/tour/self-types.md b/_fr/tour/self-types.md new file mode 100644 index 0000000000..9d82783417 --- /dev/null +++ b/_fr/tour/self-types.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Self-types +partof: scala-tour + +num: 23 + +language: fr + +next-page: implicit-parameters +previous-page: compound-types +--- diff --git a/_fr/tour/singleton-objects.md b/_fr/tour/singleton-objects.md new file mode 100644 index 0000000000..93788c0f34 --- /dev/null +++ b/_fr/tour/singleton-objects.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Singleton Objects +partof: scala-tour + +num: 12 + +language: fr + +next-page: regular-expression-patterns +previous-page: pattern-matching +--- diff --git a/_fr/tour/tour-of-scala.md b/_fr/tour/tour-of-scala.md new file mode 100644 index 0000000000..cb9fb2fcc6 --- /dev/null +++ b/_fr/tour/tour-of-scala.md @@ -0,0 +1,90 @@ +--- +layout: tour +title: Introduction +partof: scala-tour + +num: 1 +language: fr +next-page: basics + +--- + +## Bienvenue au tour +Ce tour contient une introduction morceaux par morceaux aux fonctionnalités les plus fréquemment +utilisées en Scala. Il est adressé aux novices de Scala. + +Ceci est un bref tour du language, non pas un tutoriel complet. +Si vous recherchez un guide plus détaillé, il est préférable d'opter pour [un livre](/books.html) ou de consulter +[d'autres ressources](/learn.html). + +## Qu'est-ce que le Scala ? +Scala est un langage de programmation à multiples paradigmes désigné pour exprimer des motifs de programmation communs de +façon concise, élégante et robuste. Il intègre sans problème les fonctionnalités des langages orientés objet et des +langages fonctionnels. + +## Scala est orienté objet ## +Scala est un langage purement orienté objet dans le sens où [toute valeur est un objet](unified-types.html). +Les types et les comportements de ces objets sont décrits par des [classes](classes.html) et des trait [traits](traits.html). +Les classes peuvent être étendues à travers des sous-classes et grâce à un système flexible de [composition de classes](mixin-class-composition.html). + +## Scala est fonctionnel ## +Scala est également un langage fonctionnel dans le sen où [toute fonction est une valeur](unified-types.html). +Scala propose une [syntaxe légère](basics.html) pour définir des fonctions anonymes, supporte des +[fonctions de haut niveau](higher-order-functions.html), autorise les fonctions [imbriquées](nested-functions.html) et +supporte le [currying](multiple-parameter-lists.html). +Les [case class](case-classes.html) de Scala et leur système intégré de [reconnaissance de motifs](pattern-matching.html) +permettent de construire des types algébriques utilisés dans de nombreux langages de programmation. +Les [objets singleton](singleton-objects.html) fournissent une façon pratique de regrouper des fonctions qui ne sont pas +membres d'une classe. + +De plus, la notion de reconnaissance de motifs de Scala s'étend naturellement au +[traitement des données XML](https://github.com/scala/scala-xml/wiki/XML-Processing) avec l'aide des +[patrons d'expressions régulières](regular-expression-patterns.html), grâce à une extension générale via des +[objets extracteurs](extractor-objects.html). Dans ce contexte, les [for comprehensions](for-comprehensions.html) sont +utiles pour formuler des requêtes. Ces fonctionnalités font de Scala un langage idéal pour développer des applications +comme des services Web. + +## Scala est fortement typé ## +A la compilation, le système de type expressif de Scala renforce l'utilisation des abstractions d'une manière +sécurisée et cohérente. En particulier, ce système de type supporte : + +* Les [classes génériques](generic-classes.html) +* Les [annotations variables](variances.html) +* Les limites de type [supérieures](upper-type-bounds.html) and [inférieures](lower-type-bounds.html) +* Les [classes internes](inner-classes.html) et les membres d'objets de [types abstraits](abstract-type-members.html) +* Les [types composés](compound-types.html) +* Les [auto-références explicitement typées](self-types.html) +* Les [paramètres](implicit-parameters.html) et les [conversions](implicit-conversions.html) implicites +* Les [méthodes polymorphiques](polymorphic-methods.html) + +L'[inférence de type](type-inference.html) signifie que l'utilisateur n'est pas obligé d'annoter son code avec des +informations redondantes. Rassemblées, toutes ces fonctionnalités fournissent une base solide pour la ré-utilisation +sécurisée d'abstractions de programmation et pour une extension sûre au niveau des types de programme. + +## Scala est extensible ## + +En pratique, le développement d'applications dans un domaine spécifique demande souvent des extensions de langage propre +à ce domaine. Scala fournit une combinaison de mécaniques de langage unique qui rend simple l'ajout de nouvelles +constructions de langage avec l'importation de nouvelles librairies. + +Dans beaucoup de cas, cela peut être fait sans utiliser des outils de méta-programmation, comme les macros. +En voici quelques exemples : + +* Les [classes implicites](/overviews/core/implicit-classes.html) permettent d'ajouter des méthodes supplémentaires à des types existants. +* L'[interpolation de String](/overviews/core/string-interpolation.html) est extensible par l'utilisateur avec des interpolateurs personnalisés. + +## Scala interagit ## + +Scala est conçu pour interagir proprement avec le populaire Java Runtime Environment (JRE). En particulier, l'interaction +avec le langage de programmation orienté objet le plus populaire du moment, Java, est la plus transparente possible. +Les nouvelles fonctionnalités Java comme les SAMs, les [lambdas](higher-order-functions.html), les [annotations](annotations.html), +et les [classes génériques](generic-classes.html) ont des équivalents directs en Scala. + +Il existe des fonctionnalités Scala sans équivalent Java, comme les [valeurs par défaut](default-parameter-values.html) et les +[paramètres nommés](named-arguments.html), qui se compilent d'une façon la plus proche de Java possible. Scala possède le +même modèle de compilation que Java (compilation séparée, chargement dynamique des classes) et permet d'avoir accès à des +milliers de librairies de haute qualité. + +## Bon tour ! + +Merci de continuer à la [page suivante](basics.html) pour en savoir plus. diff --git a/_fr/tour/traits.md b/_fr/tour/traits.md new file mode 100644 index 0000000000..fb57d520aa --- /dev/null +++ b/_fr/tour/traits.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Traits +partof: scala-tour + +num: 5 + +language: fr + +next-page: tuples +previous-page: classes +--- \ No newline at end of file diff --git a/_fr/tour/tuples.md b/_fr/tour/tuples.md new file mode 100644 index 0000000000..74cd02ff85 --- /dev/null +++ b/_fr/tour/tuples.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Tuples +partof: scala-tour + +num: + +language: fr + +next-page: mixin-class-composition +previous-page: traits +--- \ No newline at end of file diff --git a/_fr/tour/type-inference.md b/_fr/tour/type-inference.md new file mode 100644 index 0000000000..019ed21ef5 --- /dev/null +++ b/_fr/tour/type-inference.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Type Inference +partof: scala-tour + +num: 27 + +language: fr + +next-page: operators +previous-page: polymorphic-methods +--- diff --git a/_fr/tour/unified-types.md b/_fr/tour/unified-types.md new file mode 100644 index 0000000000..d914ee3fd0 --- /dev/null +++ b/_fr/tour/unified-types.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Unified Types +partof: scala-tour + +num: 3 + +language: fr + +next-page: classes +previous-page: basics +--- \ No newline at end of file diff --git a/_fr/tour/upper-type-bounds.md b/_fr/tour/upper-type-bounds.md new file mode 100644 index 0000000000..f47c6a4e30 --- /dev/null +++ b/_fr/tour/upper-type-bounds.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Upper Type Bounds +partof: scala-tour + +num: 18 + +language: fr + +next-page: lower-type-bounds +previous-page: variances +--- diff --git a/_fr/tour/variances.md b/_fr/tour/variances.md new file mode 100644 index 0000000000..5f535d303b --- /dev/null +++ b/_fr/tour/variances.md @@ -0,0 +1,12 @@ +--- +layout: tour +title: Variance +partof: scala-tour + +num: 17 + +language: fr + +next-page: upper-type-bounds +previous-page: generic-classes +--- diff --git a/_fr/tutorials/scala-for-java-programmers.md b/_fr/tutorials/scala-for-java-programmers.md index b89649f1fa..0b9d3ffa63 100644 --- a/_fr/tutorials/scala-for-java-programmers.md +++ b/_fr/tutorials/scala-for-java-programmers.md @@ -20,9 +20,9 @@ des connaissances de base sur la programmation orientée objet, particulièremen ## Un premier exemple -Commençons par écrire le célèbre programme *Hello world*. +Commençons par écrire le célèbre programme *Hello world*. Bien que simple, il permet de découvrir plusieurs fonctionnalités du language -avec peu de de connaissance préalable de Scala. Voilà à quoi il ressemble : +avec peu de connaissance préalable de Scala. Voilà à quoi il ressemble : object HelloWorld { def main(args: Array[String]): Unit = { @@ -106,7 +106,7 @@ l'astérisque (`*`). C'est parce que l'astérisque est un identifiant valide en un nom de méthode), comme nous le verrons plus tard. Par conséquent, la déclaration d'importation dans la seconde ligne importe tous les membres de la classe -`DateFormat`. Cela rend la méthode statique `getDateInstance` et le champ statiques `LONG` +`DateFormat`. Cela rend la méthode statique `getDateInstance` et le champ statique `LONG` directement visibles. Dans la méthode `main`, nous avons tout d'abord créé une instance de la classe Java `Date` @@ -141,7 +141,7 @@ De fait, une expression arithmétique comme la suivante : 1 + 2 * 3 / x -consiste exclusivement en des appels de méthodes, parce qu il est équivalent à l'expression +consiste exclusivement en des appels de méthodes, parce qu'il est équivalent à l'expression suivante, comme nous l'avons vu dans la section précédente : 1.+(2.*(3)./(x) @@ -250,7 +250,7 @@ malheureusement aucune règle simple pour savoir dans quel cas il est capable de ce n'est pas généralement un problème car le compilateur se plaint quand il n'est pas capable d'inférer un type qui n'a pas été donné explicitement. Une règle simple que les développeurs débutant en Scala devraient suivre est d'essayer d'omettre les déclarations de type qui semblent être faciles à -déduire et voir si le compilateur ne renvoie pas d'erreur. Après quelques temps, le développeur devrait +déduire et voir si le compilateur ne renvoie pas d'erreur. Après quelque temps, le développeur devrait avoir une bonne idée de quand il peut omettre les types et quand il faut les spécifier explicitement. ### Les méthodes sans arguments @@ -267,7 +267,7 @@ leur nom pour les appeler, comme démontré dans l'exemple suivant : Il serait plus agréable de pouvoir accéder à la partie réelle et imaginaire comme si elles étaient des champs, sans ajouter une paire de parenthèses vides. C'est parfaitement faisable en Scala, simplement en -les définissant comme des méthodes *sans argument*. De telles méthodes différents des méthodes avec +les définissant comme des méthodes *sans argument*. De telles méthodes diffèrent des méthodes avec aucun argument : elles n'ont pas de parenthèses après leur nom, que ce soit dans leur déclaration ou lors de leur utilisation. Notre classe `Complexe` peut être réécrite de cette façon : @@ -317,11 +317,11 @@ simples composées de sommes, de constantes numériques et de variables. Deux ex sont `1+2` et `(x+x)+(7+y)`. Nous devons d'abord décider d'une représentation pour de telles expressions. -La manière la plus naturelle est un arbre où chaque noeud représente une opération (ici, une addition) et +La manière la plus naturelle est un arbre où chaque nœud représente une opération (ici, une addition) et chaque feuille est une valeur (ici des constantes ou variables). En Java, un tel arbre serait représenté par une super classe abstraite pour les arbres et une -sous classe concrète pour chaque noeud et feuille. Dans un langage de programmation fonctionnelle, +sous classe concrète pour chaque nœud et feuille. Dans un langage de programmation fonctionnelle, on utiliserait plutôt un type de donnée algébrique pour faire la même chose. Scala fournit le concept de *case class* qui est quelque part entre ces deux concepts. Voici comment elles peuvent être utilisées pour définir le type des arbres pour notre exemple : @@ -347,7 +347,7 @@ différent des classes traditionnelles en différents points : comme nous le verrons plus bas. Maintenant que nous avons défini le type de données pour représenter nos expressions arithmétiques, -il est temps de définir des opérations pour les manipuler. Nous allons commencer avec une fonction +il est temps de définir des opérations pour les manipuler. Nous allons commencer par une fonction pour évaluer une expression dans un certain *environnement*. Le but de cet environnement est de donner des valeurs aux variables. Par exemple, l'expression `x+1` évaluée dans un environnement qui associe la valeur `5` à la variable `x`, écrit `{ x -> 5 }`, donne comme résultat `6`. @@ -398,11 +398,11 @@ devrait être claire : motif décrit à gauche de la flèche ; 2. Si la première vérification échoue, c'est-à-dire que l'arbre n'est pas une `Somme`, on continue et on vérifie si `a` est une `Var`. Si c'est le cas, - il relie le nom contenu dans le noeud `Var` à une variable `n` et + il relie le nom contenu dans le nœud `Var` à une variable `n` et il traite l'expression à droite de la flèche ; 3. Si la deuxième vérification échoue, c'est-à-dire que l'arbre n'est ni une `Somme` ni une `Var`, on vérifie si l'arbre est un `Const`. Si - c'est le cas, il relie la valeur contenue dans le noeud `Const` à une + c'est le cas, il relie la valeur contenue dans le nœud `Const` à une variable `v` et il traite l'expression à droite de la flèche ; 4. Enfin, si toutes les vérifications échouent, une exception est levée pour signaler l'échec de l'expression. Dans notre cas, cela pourrait arriver si @@ -420,13 +420,13 @@ la définition de méthodes dans les case class tout comme dans les classes norm Décider d'utiliser un pattern matching ou des méthodes est donc une question de goût mais a aussi des implications importantes sur l'extensibilité : -- quand on utilise des méthodes, il est facile d'ajouter un nouveau type de noeud en même temps +- quand on utilise des méthodes, il est facile d'ajouter un nouveau type de nœud en même temps qu'une nouvelle sous classe de `Arbre` est définie. Par contre, ajouter une nouvelle opération pour manipuler un arbre est fastidieux car il demande de modifier toutes les sous classes de `Arbre` ; - quand on utilise un pattern matching, la situation est inversée : ajouter un - nouveau type de noeud demande la modification de toutes les fonctions qui effectuent - un pattern matching sur un arbre pour prendre en compte le nouveau noeud. + nouveau type de nœud demande la modification de toutes les fonctions qui effectuent + un pattern matching sur un arbre pour prendre en compte le nouveau nœud. Par contre, ajouter une nouvelle opération est facile en la définissant en tant que fonction indépendante. @@ -439,7 +439,7 @@ garder à l'esprit les règles suivantes par rapport à cette opération : variable utilisée pour la dérivation et zéro sinon ; 3. la dérivée d'une constante est zéro. -Ces règles peut être traduites presque littéralement en du code Scala +Ces règles peuvent presque être traduites littéralement en du code Scala pour obtenir la définition suivante : def derivee(a: Arbres, v: String): Arbres = a match { @@ -503,7 +503,7 @@ Notez que depuis Java 8, les interfaces Java peut aussi contenir du code, soit en utilisant le mot clé `default` soit avec des méthodes statiques. Pour s'apercevoir de l'utilité des traits, regardons un exemple classique : -les objets ordonnés. Il est souvent utile de pouvoir comparer entre eux des objets +les objets ordonnés. Il est souvent utile de pouvoir comparer des objets d'une même classe, par exemple pour les trier. En Java, les objets qui sont comparables implémentent l'interface `Comparable`. En Scala, on peut faire un peu mieux qu'en Java en définissant @@ -616,7 +616,7 @@ Les développeurs Java se retrouvent à utiliser `Object`, le super type de tous les objets. Cependant, cette solution est loin d'être idéale, puisqu'elle ne marche pas pour les types basiques (`int`, `long`, `float`, etc.) et cela implique que le développeur -devra faire un certain nombre de conversion de types. +devra faire un certain nombre de conversions de types. Scala rend possible la définition de classes (et de méthodes) génériques pour résoudre ce problème. Examinons ceci au travers d'un exemple d'une diff --git a/_getting-started/intellij-track/building-a-scala-project-with-intellij-and-sbt.md b/_getting-started/intellij-track/building-a-scala-project-with-intellij-and-sbt.md index c575d4bfde..36627dcf29 100644 --- a/_getting-started/intellij-track/building-a-scala-project-with-intellij-and-sbt.md +++ b/_getting-started/intellij-track/building-a-scala-project-with-intellij-and-sbt.md @@ -54,9 +54,9 @@ but here's a glance at what everything is for: 1. On the **Project** panel on the left, expand `SbtExampleProject` => `src` => `main` 1. Right-click `scala` and select **New** => **Package** -1. Name the package `example` and click **OK**. +1. Name the package `example` and click **OK** (or just press the Enter or Return key). 1. Right-click the package `example` and select **New** => **Scala class**. -1. Name the class `Main` and change the **Kind** to `object`. +1. Name the class `Main` and change the **Kind** to `Object`. 1. Change the code in the class to the following: ``` diff --git a/_getting-started/intellij-track/getting-started-with-scala-in-intellij.md b/_getting-started/intellij-track/getting-started-with-scala-in-intellij.md index 2e24d76826..6bab3d3d14 100644 --- a/_getting-started/intellij-track/getting-started-with-scala-in-intellij.md +++ b/_getting-started/intellij-track/getting-started-with-scala-in-intellij.md @@ -40,7 +40,7 @@ take a few minutes but subsequent projects can use the same SDK. ## Writing code 1. On the **Project** pane on the left, right-click `src` and select -**New** => **Scala class**. If you don't see **Scala class**, right-click on **HelloWorld** and click on **Add Framework Support...**, select **Scala** and proceed. If you see **Error: library is not specified**, you can either click download button, or select the library path manually. +**New** => **Scala class**. If you don't see **Scala class**, right-click on **HelloWorld** and click on **Add Framework Support...**, select **Scala** and proceed. If you see **Error: library is not specified**, you can either click download button, or select the library path manually. If you only see **Scala Worksheet** try expanding the `src` folder and its `main` subfolder, and right-click on the `scala` folder. 1. Name the class `Hello` and change the **Kind** to `object`. 1. Change the code in the class to the following: diff --git a/_it/tutorials/scala-for-java-programmers.md b/_it/tutorials/scala-for-java-programmers.md index fa4327bbeb..5cf8cb4b1c 100644 --- a/_it/tutorials/scala-for-java-programmers.md +++ b/_it/tutorials/scala-for-java-programmers.md @@ -73,7 +73,7 @@ avrà il nome `HelloWorld.class` e conterrà una classe che può essere direttamente eseguita con il comando `scala`, come mostra la seguente sezione. -### Eseguimo l'esempio +### Eseguiamo l'esempio Una volta compilato il programma può esser facilmente eseguito con il comando scala. L'uso è molto simile al comando java ed accetta le stesse @@ -91,13 +91,13 @@ codice Java. Tutte le classi del package `java.lang` sono importate di default mentre le altre richiedono l’esplicito import. Osserviamo un esempio che lo dimostra. Vogliamo ottenere la data -corrente e formattarla in accordo con la convezione usata in uno +corrente e formattarla in accordo con la convenzione usata in uno specifico paese del mondo, diciamo la Francia. (Altre regioni, come la parte di lingua francese della Svizzera, utilizzano le stesse convenzioni.) Le librerie delle classi Java definiscono potenti classi di utilità come `Date` e `DateFormat`. Poiché Scala interagisce direttamente con Java, non -esistono le classi equivalenti nella libreria delle classi di Scala--possiamo +esistono le classi equivalenti nella libreria delle classi di Scala; possiamo semplicemente importare le classi dei corrispondenti package Java: import java.util.{Date, Locale} @@ -112,7 +112,7 @@ semplicemente importare le classi dei corrispondenti package Java: } } -L’istruzione import di Scala è molto simile all’equivalente in Java +L’istruzione `import` di Scala è molto simile all’equivalente in Java tuttavia, risulta essere più potente. Più classi possono essere importate dallo stesso package includendole in parentesi graffe come nella prima riga di codice precedentemente riportato. Un’altra differenza è evidente @@ -130,7 +130,7 @@ Java che di default contiene la data corrente. Successivamente, definiamo il formato della data usando il metodo statico `getDateInstance` importato precedentemente. Infine, stampiamo la data corrente, formattata secondo la localizzazione scelta, con l’istanza `DateFormat`; quest’ultima linea mostra -un’importante proprietà di Scala.I metodi che prendono un argomento possono +un’importante proprietà di Scala. I metodi che prendono un argomento (ed uno soltanto) possono essere usati con una sintassi non fissa. Questa forma dell’espressione df format now @@ -582,7 +582,7 @@ definendo la classe `Date` come segue: La parte importante qui è la dichiarazione `extends Ord` che segue il nome della classe e dei parametri. Dichiara che la classe `Date` eredita il -codice dal trait `extends Ord`. +codice dal trait `Ord`. Successivamente ridefiniamo il metodo `equals`, ereditato da `Object`, in modo tale che possa confrontare in modo corretto le date confrontando @@ -694,6 +694,6 @@ poiché è stata dichiarata per memorizzare un intero. Questo documento ha fornito una veloce introduzione del linguaggio Scala e presentato alcuni esempi di base. Il lettore interessato può continuare, per -esempio, leggendo il documento *Scala By Example* che contiene esempi molti più +esempio, leggendo il documento [*Tour of Scala*](https://docs.scala-lang.org/tour/tour-of-scala.html) che contiene esempi molti più avanzati e consultare al bisogno la documentazione *Scala Language Specification*. diff --git a/_ja/tour/annotations.md b/_ja/tour/annotations.md index e3f705bf1d..7347894b70 100644 --- a/_ja/tour/annotations.md +++ b/_ja/tour/annotations.md @@ -8,7 +8,7 @@ discourse: true partof: scala-tour num: 32 -next-page: default-parameter-values +next-page: packages-and-imports previous-page: by-name-parameters --- diff --git a/_ko/tour/annotations.md b/_ko/tour/annotations.md index 8e0ea7e0f4..924664303d 100644 --- a/_ko/tour/annotations.md +++ b/_ko/tour/annotations.md @@ -6,7 +6,7 @@ partof: scala-tour num: 31 language: ko -next-page: default-parameter-values +next-page: packages-and-imports previous-page: automatic-closures --- diff --git a/_overviews/jdk-compatibility/overview.md b/_overviews/jdk-compatibility/overview.md index 604bbb18bf..fd20db5a37 100644 --- a/_overviews/jdk-compatibility/overview.md +++ b/_overviews/jdk-compatibility/overview.md @@ -12,10 +12,10 @@ Sometimes new JVM and JDK (Java Development Kit) versions require us to update S | JDK version | Minimum Scala versions | Recommended Scala versions | |:-----------:|:---------------------------------|:-----------------------------------------------------------| -| 13, 14, 15 | 2.13.2, 2.12.11 | 2.13.3, 2.12.12 | -| 12 | 2.13.1, 2.12.9 | 2.13.3, 2.12.12 | -| 11 | 2.13.0, 2.12.4, 2.11.12 | 2.13.3, 2.12.12, 2.11.12 | -| 8 | 2.13.0, 2.12.0, 2.11.0, 2.10.2 | 2.13.3, 2.12.12, 2.11.12, 2.10.7 | +| 13, 14, 15 | 2.13.2, 2.12.11 | 2.13.4, 2.12.12 | +| 12 | 2.13.1, 2.12.9 | 2.13.4, 2.12.12 | +| 11 | 2.13.0, 2.12.4, 2.11.12 | 2.13.4, 2.12.12, 2.11.12 | +| 8 | 2.13.0, 2.12.0, 2.11.0, 2.10.2 | 2.13.4, 2.12.12, 2.11.12, 2.10.7 | | 6, 7 | 2.11.0, 2.10.0 | 2.11.12, 2.10.7 | Even when a version combination isn't listed as supported, most features may still work. (But Scala 2.12+ definitely doesn't work at all on JDK 6 or 7.) diff --git a/_overviews/plugins/index.md b/_overviews/plugins/index.md index 13f1666a2d..91978ab80b 100644 --- a/_overviews/plugins/index.md +++ b/_overviews/plugins/index.md @@ -17,6 +17,13 @@ compiler. It does not go into depth on how to make your plugin actually do something useful, but just shows the basics needed to write a plugin and hook it into the Scala compiler. +## You can read, but you can also watch TV + +The contents of this guide overlaps substantially with Seth Tisue's +talk "Scala Compiler Plugins 101" ([32 minute video](https://www.youtube.com/watch?v=h5NZjuxS5Qo)). +Although the talk is from April 2018, nearly all of the information +in it still applies (as of November 2020). + ## When to write a plugin Plugins let you modify the behavior of the Scala compiler without @@ -68,6 +75,7 @@ All of this is then packaged in a JAR file. To use the plugin, a user adds the JAR file to their compile-time classpath and enables it by invoking `scalac` with `-Xplugin:...`. +(Some build tools provide shortcuts for this; see below.) All of this will be described in more detail below. @@ -147,6 +155,12 @@ aspects of note. desire on the given compilation unit. Usually this involves examining the trees within the unit and doing some transformation on the tree. +- The pattern match inside the body of `apply` shows one way of + detecting certain tree shapes in user code. + (Quasiquotes are another way.) `Apply` denotes a method call, + and `Select` denotes the "selection" of a member, such as `a.b`. + The details of tree processing are out of scope for this document, + but see "Going further", below, for links to further documentation. The `runsAfter` method gives the plugin author control over when the phase is executed. As seen above, it is expected to return a list of @@ -187,6 +201,11 @@ with that file plus your compiled code: cp scalac-plugin.xml classes (cd classes; jar cf ../divbyzero.jar .) +That's how it works with no build tool. If you are using sbt to build +your plugin, then the XML file goes in `src/main/resources`. + +## Using a plugin with scalac + Now you can use your plugin with `scalac` by adding the `-Xplugin:` option: @@ -196,23 +215,44 @@ option: ^ one error found +## Publishing your plugin + When you are happy with how the plugin behaves, you may wish to publish the JAR to a Maven or Ivy repository where it can be resolved -by a build tool. +by a build tool. (For testing purposes, you can also publish it to +your local machine only. In sbt, this is accomplished with +`publishLocal`.) + +In most respects, compiler plugins are ordinary Scala libraries, +so publishing a plugin is like publishing any library. +See the [Library Author Guide]({{site.baseurl}}/overviews/contributors/index.html) +and/or your build tool's documentation on publishing. -sbt, for example, provides an `addCompilerPlugin` method you can +## Using a plugin from sbt + +To make it convenient for end users to use your plugin once it has +been published, sbt provides an `addCompilerPlugin` method you can call in your build definition, e.g.: - addCompilerPlugin("org.divbyzero" % "divbyzero" % "1.0") + addCompilerPlugin("org.divbyzero" %% "divbyzero" % "1.0") + +`addCompilerPlugin` performs multiple actions. It adds the JAR to the +classpath (the compilation classpath only, not the runtime classpath) +via `libraryDependencies`, and it also customizes `scalacOptions` to +enable the plugin using `-Xplugin`. + +For more details, see [Compiler Plugin +Support](https://www.scala-sbt.org/1.x/docs/Compiler-Plugins.html) in +the sbt manual. -Note however that `addCompilerPlugin` only adds the JAR to the -compilation classpath; it doesn't actually enable the plugin. To -do that, you must customize `scalacOptions` to include the appropriate -`-Xplugin` call. To shield users from having to know this, it's -relatively common for compiler plugin authors to also write an -accompanying sbt plugin that takes of customizing the classpath and -compiler options appropriately. Then using your plugin only requires -adding an `addSbtPlugin(...)` call to `project/plugins.sbt`. +## Developing compiler plugins with an IDE + +Internally, the use of path-dependent types in the Scala compiler +may confuse some IDEs such as IntelliJ. Correct plugin code may +sometimes be highlighted as erroneous. The IDE is usually still +useful under these circumstances, but remember to take its feedback +with a grain of salt. If the error highlighting is distracting, +the IDE may have a setting where you can disable it. ## Useful compiler options @@ -317,9 +357,12 @@ behavior other than to print out its option. ## Going further For the details on how to make your plugin accomplish some task, you -must consult other documentation on compiler internals (such as the -documentation on [Symbols, Trees, and Types]({{site.baseurl -}}/overviews/reflection/symbols-trees-types.html). +must consult other documentation on compiler internals. Relevant +documents include: + +* [Symbols, Trees, and Types]({{site.baseurl}}/overviews/reflection/symbols-trees-types.html) is the single most important reference about the data structures used inside the compiler. +* [Quasiquotes]({{site.baseurl}}/overviews/quasiquotes/intro.html) are useful for pattern matching on ASTs. + * The [syntax summary]({{site.baseurl}}/overviews/quasiquotes/syntax-summary.html) in the quasiquotes guide is a useful concordance between user-level syntax and AST node types. It's also useful to look at other plugins and to study existing phases within the compiler source code. diff --git a/_pt-br/tour/annotations.md b/_pt-br/tour/annotations.md index a594644bd6..5d0842e42c 100644 --- a/_pt-br/tour/annotations.md +++ b/_pt-br/tour/annotations.md @@ -4,7 +4,7 @@ title: Anotações partof: scala-tour num: 31 -next-page: default-parameter-values +next-page: packages-and-imports previous-page: automatic-closures language: pt-br --- diff --git a/_ru/overviews/collections-2.13/seqs.md b/_ru/overviews/collections-2.13/seqs.md index e85e6f1eb3..c5557bdd40 100644 --- a/_ru/overviews/collections-2.13/seqs.md +++ b/_ru/overviews/collections-2.13/seqs.md @@ -76,7 +76,7 @@ language: ru | `xs intersect ys` |Операция пересечения на множестве между последовательностей `xs` и `ys`, сохраняющее порядок элементов в `xs`.| | `xs diff ys` |Операция расхождения на множестве между последовательностей `xs` и `ys`, сохраняющее порядок элементов в `xs`.| | `xs.distinct` |Подпоследовательность `xs`, которая не содержит дублирующих друг друга элементов.| -| `xs distinctBy f` |Подпоследовательность `xs`, которая не содержит дублирующего элемента после применения функции преобразования `f`. Например, `List("foo", "bar", "quux").distinctBy(_.length) == List("foo", "bar")`| +| `xs distinctBy f` |Подпоследовательность `xs`, которая не содержит дублирующего элемента после применения функции преобразования `f`. Например, `List("foo", "bar", "quux").distinctBy(_.length) == List("foo", "quux")`| У трейта [Seq](https://www.scala-lang.org/api/current/scala/collection/Seq.html) есть два дочерних трейта [LinearSeq](https://www.scala-lang.org/api/current/scala/collection/LinearSeq.html), и [IndexedSeq](https://www.scala-lang.org/api/current/scala/collection/IndexedSeq.html). Они не добавляют никаких новых операций, но у каждого из них разные характеристики производительности: у LinearSeq эффективные операции `head` и `tail`, в то время как у IndexedSeq эффективные операции `apply`, `length` и (если мутабельная) `update`. Часто используемые варианты LinearSeq - это `scala.collection.immutable.List` и `scala.collection.immutable.LazyList`. А наиболее часто используемые IndexedSeq - это `scala.Array` и `scala.collection.mutable.ArrayBuffer`. Класс `Vector` представляет собой компромисс между IndexedSeq и LinearSeq. У него эффективные, как обращение по индексу, так и последовательный обход элементов. Поэтому вектора хорошая основа для смешанных моделей доступа, где используются как индексированный, так и последовательный доступ. Позже мы расскажем больше о [векторах](concrete-immutable-collection-classes.html). diff --git a/_ru/tour/annotations.md b/_ru/tour/annotations.md index 50829901d4..23bdb8fad6 100644 --- a/_ru/tour/annotations.md +++ b/_ru/tour/annotations.md @@ -8,7 +8,7 @@ partof: scala-tour num: 32 language: ru -next-page: default-parameter-values +next-page: packages-and-imports previous-page: by-name-parameters --- diff --git a/_ru/tour/default-parameter-values.md b/_ru/tour/default-parameter-values.md index 7bf61e5430..0286d62e18 100644 --- a/_ru/tour/default-parameter-values.md +++ b/_ru/tour/default-parameter-values.md @@ -9,7 +9,7 @@ partof: scala-tour num: 33 language: ru next-page: named-arguments -previous-page: annotations +previous-page: classes prerequisite-knowledge: named-arguments, function syntax --- diff --git a/_ru/tour/packages-and-imports.md b/_ru/tour/packages-and-imports.md index ef7865e3e7..563871406a 100644 --- a/_ru/tour/packages-and-imports.md +++ b/_ru/tour/packages-and-imports.md @@ -8,7 +8,7 @@ partof: scala-tour num: 35 language: ru -previous-page: named-arguments +previous-page: annotations next-page: package-objects --- diff --git a/_ru/tour/traits.md b/_ru/tour/traits.md index 4fea28e80f..468e2b7f60 100644 --- a/_ru/tour/traits.md +++ b/_ru/tour/traits.md @@ -9,7 +9,7 @@ partof: scala-tour num: 5 language: ru next-page: tuples -previous-page: classes +previous-page: named-arguments topics: traits prerequisite-knowledge: expressions, classes, generics, objects, companion-objects diff --git a/_style/index.md b/_style/index.md index 619c864e5e..279779349f 100644 --- a/_style/index.md +++ b/_style/index.md @@ -55,7 +55,6 @@ This document is intended to outline some basic Scala stylistic guidelines which - [Trivial Conditionals](control-structures.html#trivial-conditionals) - [Method Invocation](method-invocation.html) - [Arity-0](method-invocation.html#arity-0) - - [Postfix Notation](method-invocation.html#postfix-notation) - [Arity-1 (Infix Notation)](method-invocation.html#arity-1-infix-notation) - [Symbolic Methods/Operators](method-invocation.html#symbolic-methodsoperators) - [Higher-Order Functions](method-invocation.html#higher-order-functions) diff --git a/_style/method-invocation.md b/_style/method-invocation.md index 694552afba..861d07dba6 100644 --- a/_style/method-invocation.md +++ b/_style/method-invocation.md @@ -56,30 +56,6 @@ readability and will make it much easier to understand at a glance the most basic operation of any given method. Resist the urge to omit parentheses simply to save two characters! -### Postfix Notation - -Scala allows methods that take no arguments to be invoked using postfix notation: - - // recommended - names.toList - - // discourage - names toList - -This style is unsafe, and should not be used. Since semicolons are -optional, the compiler will attempt to treat it as an infix method -if it can, potentially taking a term from the next line. - - names toList - val answer = 42 // will not compile! - -This may result in unexpected compile errors at best, and happily -compiled faulty code at worst. Although the syntax is used by some -DSLs, it should be considered deprecated, and avoided. - -Since Scala 2.10, using postfix operator notation will result in a -compiler warning. - ## Arity-1 (Infix Notation) Scala has a special punctuation-free syntax for invoking methods of arity-1 diff --git a/_th/tour/annotations.md b/_th/tour/annotations.md index 4762815311..fb171607d0 100644 --- a/_th/tour/annotations.md +++ b/_th/tour/annotations.md @@ -7,6 +7,6 @@ num: 30 language: th -next-page: default-parameter-values +next-page: packages-and-imports previous-page: by-name-parameters --- diff --git a/_tour/generic-classes.md b/_tour/generic-classes.md index cf654cc4aa..035a6c0ee5 100644 --- a/_tour/generic-classes.md +++ b/_tour/generic-classes.md @@ -17,7 +17,8 @@ Generic classes take a type as a parameter within square brackets `[]`. One conv ```tut class Stack[A] { private var elements: List[A] = Nil - def push(x: A) { elements = x :: elements } + def push(x: A): Unit = + elements = x :: elements def peek: A = elements.head def pop(): A = { val currentTop = peek diff --git a/_tour/named-arguments.md b/_tour/named-arguments.md index 3b8159bb99..db54d951e3 100644 --- a/_tour/named-arguments.md +++ b/_tour/named-arguments.md @@ -29,4 +29,4 @@ Notice how the order of named arguments can be rearranged. However, if some argu printName(last = "Smith", "john") // error: positional after named argument ``` -Note that named arguments do not work with calls to Java methods. +Named arguments work with calls to Java methods, but only if the Java library in question was compiled with `-parameters`. diff --git a/_tour/self-types.md b/_tour/self-types.md index 2f659637f0..e1a80388fb 100644 --- a/_tour/self-types.md +++ b/_tour/self-types.md @@ -27,7 +27,7 @@ trait Tweeter { } class VerifiedTweeter(val username_ : String) extends Tweeter with User { // We mixin User because Tweeter required it - def username = s"real $username_" + def username = s"real $username_" } val realBeyoncé = new VerifiedTweeter("Beyoncé") diff --git a/_tour/variances.md b/_tour/variances.md index 582d126c74..6d70f615dc 100644 --- a/_tour/variances.md +++ b/_tour/variances.md @@ -32,7 +32,7 @@ case class Cat(name: String) extends Animal case class Dog(name: String) extends Animal ``` -Both `Cat` and `Dog` are subtypes of `Animal`. The Scala standard library has a generic immutable `sealed abstract class List[+A]` class, where the type parameter `A` is covariant. This means that a `List[Cat]` is a `List[Animal]` and a `List[Dog]` is also a `List[Animal]`. Intuitively, it makes sense that a list of cats and a list of dogs are each lists of animals, and you should be able to substitute either of them for a `List[Animal]`. +Both `Cat` and `Dog` are subtypes of `Animal`. The Scala standard library has a generic immutable `sealed abstract class List[+A]` class, where the type parameter `A` is covariant. This means that a `List[Cat]` is a `List[Animal]` and a `List[Dog]` is also a `List[Animal]`. Intuitively, it makes sense that a list of cats and a list of dogs are each lists of animals, and you should be able to use either of them for in place of `List[Animal]`. In the following example, the method `printAnimalNames` will accept a list of animals as an argument and print their names each on a new line. If `List[A]` were not covariant, the last two method calls would not compile, which would severely limit the usefulness of the `printAnimalNames` method. @@ -78,7 +78,7 @@ class CatPrinter extends Printer[Cat] { } ``` -If a `Printer[Cat]` knows how to print any `Cat` to the console, and a `Printer[Animal]` knows how to print any `Animal` to the console, it makes sense that a `Printer[Animal]` would also know how to print any `Cat`. The inverse relationship does not apply, because a `Printer[Cat]` does not know how to print any `Animal` to the console. Therefore, we should be able to substitute a `Printer[Animal]` for a `Printer[Cat]`, if we wish, and making `Printer[A]` contravariant allows us to do exactly that. +If a `Printer[Cat]` knows how to print any `Cat` to the console, and a `Printer[Animal]` knows how to print any `Animal` to the console, it makes sense that a `Printer[Animal]` would also know how to print any `Cat`. The inverse relationship does not apply, because a `Printer[Cat]` does not know how to print any `Animal` to the console. Therefore, we should be able to use a `Printer[Animal]` in place of `Printer[Cat]`, if we wish, and making `Printer[A]` contravariant allows us to do exactly that. ```tut def printMyCat(printer: Printer[Cat], cat: Cat): Unit = @@ -134,7 +134,7 @@ abstract class SmallAnimal extends Animal case class Mouse(name: String) extends SmallAnimal ``` -Suppose we're working with functions that accept types of animals, and return the types of food they eat. If we would like a `Cat => SmallAnimal` (because cats eat small animals), but are given a `Animal => Mouse` instead, our program will still work. Intuitively an `Animal => Mouse` will still accept a `Cat` as an argument, because a `Cat` is an `Animal`, and it returns a `Mouse`, which is also a `SmallAnimal`. Since we can safely and invisibly substitute the former by the latter, we can say `Animal => Mouse` is a subtype of `Cat => SmallAnimal`. +Suppose we're working with functions that accept types of animals, and return the types of food they eat. If we would like a `Cat => SmallAnimal` (because cats eat small animals), but are given a `Animal => Mouse` instead, our program will still work. Intuitively an `Animal => Mouse` will still accept a `Cat` as an argument, because a `Cat` is an `Animal`, and it returns a `Mouse`, which is also a `SmallAnimal`. Since we can safely and invisibly substitute the former with the latter, we can say `Animal => Mouse` is a subtype of `Cat => SmallAnimal`. ### Comparison With Other Languages diff --git a/_zh-cn/overviews/reflection/.jekyll-metadata b/_zh-cn/overviews/reflection/.jekyll-metadata new file mode 100644 index 0000000000..72fc01387f Binary files /dev/null and b/_zh-cn/overviews/reflection/.jekyll-metadata differ diff --git a/_zh-cn/overviews/reflection/environment-universes-mirrors.md b/_zh-cn/overviews/reflection/environment-universes-mirrors.md new file mode 100644 index 0000000000..e3299e4dea --- /dev/null +++ b/_zh-cn/overviews/reflection/environment-universes-mirrors.md @@ -0,0 +1,178 @@ +--- +layout: multipage-overview +title: Environment, Universes, and Mirrors +partof: reflection +overview-name: Reflection + +num: 2 +language: zh-cn +--- + +EXPERIMENTAL + +## Environment + +反射环境根据反射工作是在运行时还是在编译时完成而有所不同。在运行时和编译时使用的环境之间的区别被封装在一个所谓的 *原型(universe)* 中。 +反射环境的另一个重要方面是我们可以反射的访问一组实体。这组实体由所谓的 *镜像(mirror)* 决定。 + +例如,可通过运行时反射访问的实体由`ClassloaderMirror`提供。该镜像仅提供对由特定类加载器加载的实体(包,类型和成员)的访问。 + +镜像不仅可以确定反射访问的实体集。它们还提供对这些实体执行的反射操作。例如,在运行时反射中,可以使用*调用者镜像*(invoker mirror)来调用类的方法或构造函数。 + +## Universes + +原型有两种主要类型 - 由于同时具有运行时和编译时反射功能,一个人必须使用与即将完成的工作相对应的原型。二者之一: + +- `scala.reflect.runtime.universe` 用于 **运行时反射**,或者 +- `scala.reflect.macros.Universe` 用于 **编译时反射**。 + +一个原型提供了反射中使用的所有主要概念的接口,例如类型(`Types`),树(`Trees`)和注解(`Annotations`)。 + +## Mirrors + +反射提供的所有信息都可以通过*镜像*访问。根据要获得的信息类型或要采取的反射动作,必须使用不同类型的镜像。*类加载器镜像*可用于获取类型和成员的表示。 +从类加载器镜像中,可以获得更专门的*调用者*镜像(最常用的镜像),这些镜像实现了反射调用,例如方法或构造函数调用以及字段访问。 + +总结: + +- **"类加载器" 镜像**。这些镜像将名称转换为符号 (通过方法 `staticClass`/`staticModule`/`staticPackage`)。 + +- **"调用者" 镜像**。这些镜像实现反射调用(通过方法 `MethodMirror.apply`,`FieldMirror.get`,等等。)。这些"调用者"镜像是最常用的镜像类型。 + +### Runtime Mirrors + +在运行时使用的镜像的入口点是通过`ru.runtimeMirror()`,其中`ru`是`scala.reflect.runtime.universe`。 + +一个`scala.reflect.api.JavaMirrors#runtimeMirror`的调用结果是一个类型为`scala.reflect.api.Mirrors#ReflectiveMirror`的类加载器镜像,它可以按名称加载符号。 + +一个类加载器镜像可以创建多个调用者镜像(包括`scala.reflect.api.Mirrors#InstanceMirror`,`scala.reflect.api.Mirrors#MethodMirror`,`scala.reflect.api.Mirrors#FieldMirror`,`scala.reflect.api.Mirrors#ClassMirror`,和`scala.reflect.api.Mirrors#ModuleMirror`)。 + +下面提供了这两种类型的反射镜像如何相互作用的示例。 + +### Types of Mirrors, Their Use Cases & Examples + +`ReflectiveMirror`用于按名称加载符号,并用作调用者镜像的入口。入口点:`val m = ru.runtimeMirror()`。例如: + + scala> val ru = scala.reflect.runtime.universe + ru: scala.reflect.api.JavaUniverse = ... + + scala> val m = ru.runtimeMirror(getClass.getClassLoader) + m: scala.reflect.runtime.universe.Mirror = JavaMirror ... + +`InstanceMirror`用于为方法和字段以及内部类和内部对象(模块)创建调用者镜像。入口点:`val im = m.reflect()`。例如: + + scala> class C { def x = 2 } + defined class C + + scala> val im = m.reflect(new C) + im: scala.reflect.runtime.universe.InstanceMirror = instance mirror for C@3442299e + +`MethodMirror`用于调用实例方法(Scala仅具有实例方法-对象的方法是对象实例的实例方法,可通过`ModuleMirror.instance`获得)。入口点:`val mm = im.reflectMethod()`)。例如: + + scala> val methodX = ru.typeOf[C].decl(ru.TermName("x")).asMethod + methodX: scala.reflect.runtime.universe.MethodSymbol = method x + + scala> val mm = im.reflectMethod(methodX) + mm: scala.reflect.runtime.universe.MethodMirror = method mirror for C.x: scala.Int (bound to C@3442299e) + + scala> mm() + res0: Any = 2 + +`FieldMirror`用于获取/设置实例字段(与方法类似,Scala仅具有实例字段,请参见上文)。入口点:`val fm = im.reflectField()`。例如: + + scala> class C { val x = 2; var y = 3 } + defined class C + + scala> val m = ru.runtimeMirror(getClass.getClassLoader) + m: scala.reflect.runtime.universe.Mirror = JavaMirror ... + + scala> val im = m.reflect(new C) + im: scala.reflect.runtime.universe.InstanceMirror = instance mirror for C@5f0c8ac1 + + scala> val fieldX = ru.typeOf[C].decl(ru.TermName("x")).asTerm.accessed.asTerm + fieldX: scala.reflect.runtime.universe.TermSymbol = value x + + scala> val fmX = im.reflectField(fieldX) + fmX: scala.reflect.runtime.universe.FieldMirror = field mirror for C.x (bound to C@5f0c8ac1) + + scala> fmX.get + res0: Any = 2 + + scala> fmX.set(3) + + scala> val fieldY = ru.typeOf[C].decl(ru.TermName("y")).asTerm.accessed.asTerm + fieldY: scala.reflect.runtime.universe.TermSymbol = variable y + + scala> val fmY = im.reflectField(fieldY) + fmY: scala.reflect.runtime.universe.FieldMirror = field mirror for C.y (bound to C@5f0c8ac1) + + scala> fmY.get + res1: Any = 3 + + scala> fmY.set(4) + + scala> fmY.get + res2: Any = 4 + +`ClassMirror`用于为构造函数创建调用者镜像。入口点:对于静态类`val cm1 = m.reflectClass()`,对于内部类`val mm2 = im.reflectClass()`。例如: + + scala> case class C(x: Int) + defined class C + + scala> val m = ru.runtimeMirror(getClass.getClassLoader) + m: scala.reflect.runtime.universe.Mirror = JavaMirror ... + + scala> val classC = ru.typeOf[C].typeSymbol.asClass + classC: scala.reflect.runtime.universe.Symbol = class C + + scala> val cm = m.reflectClass(classC) + cm: scala.reflect.runtime.universe.ClassMirror = class mirror for C (bound to null) + + scala> val ctorC = ru.typeOf[C].decl(ru.termNames.CONSTRUCTOR).asMethod + ctorC: scala.reflect.runtime.universe.MethodSymbol = constructor C + + scala> val ctorm = cm.reflectConstructor(ctorC) + ctorm: scala.reflect.runtime.universe.MethodMirror = constructor mirror for C.(x: scala.Int): C (bound to null) + + scala> ctorm(2) + res0: Any = C(2) + +`ModuleMirror`用于访问单例对象的实例。入口点:对于静态对象`val mm1 = m.reflectModule()`,对于内部对象`val mm2 = im.reflectModule()`。例如: + + scala> object C { def x = 2 } + defined module C + + scala> val m = ru.runtimeMirror(getClass.getClassLoader) + m: scala.reflect.runtime.universe.Mirror = JavaMirror ... + + scala> val objectC = ru.typeOf[C.type].termSymbol.asModule + objectC: scala.reflect.runtime.universe.ModuleSymbol = object C + + scala> val mm = m.reflectModule(objectC) + mm: scala.reflect.runtime.universe.ModuleMirror = module mirror for C (bound to null) + + scala> val obj = mm.instance + obj: Any = C$@1005ec04 + +### Compile-Time Mirrors + +编译时镜像仅使用类加载器镜像来按名称加载符号。 + +类加载器镜像的入口点通过`scala.reflect.macros.Context#mirror`。使用类加载器镜像的典型方法包括`scala.reflect.api.Mirror#staticClass`,`scala.reflect.api.Mirror#staticModule`和`scala.reflect.api.Mirror#staticPackage`。例如: + + import scala.reflect.macros.Context + + case class Location(filename: String, line: Int, column: Int) + + object Macros { + def currentLocation: Location = macro impl + + def impl(c: Context): c.Expr[Location] = { + import c.universe._ + val pos = c.macroApplication.pos + val clsLocation = c.mirror.staticModule("Location") // get symbol of "Location" object + c.Expr(Apply(Ident(clsLocation), List(Literal(Constant(pos.source.path)), Literal(Constant(pos.line)), Literal(Constant(pos.column))))) + } + } + +注意:有几种高级替代方法,可以避免必须手动查找符号。例如,`typeOf[Location.type].termSymbol`(如果需要`ClassSymbol`,则为`typeOf[Location].typeSymbol`),因为我们不必使用字符串来查找符号,所以它们是类型安全的。 \ No newline at end of file diff --git a/_zh-cn/overviews/reflection/typetags-manifests.md b/_zh-cn/overviews/reflection/typetags-manifests.md index 0830e50839..ab3f5d448c 100644 --- a/_zh-cn/overviews/reflection/typetags-manifests.md +++ b/_zh-cn/overviews/reflection/typetags-manifests.md @@ -5,7 +5,7 @@ partof: reflection overview-name: Reflection num: 5 -languages: zh-cn +language: zh-cn --- 与其他JVM语言一样,Scala的类型在运行时被擦除。这意味着,如果要检查某个实例的运行时类型,则可能无法访问Scala编译器在编译时可用的所有类型信息。 @@ -129,4 +129,4 @@ _注意_:这通常是通过在方法上使用隐式参数来实现的,并且 - **不支持某些manifest操作(即`<:<`, `>:>`和`typeArguments`)。** 取而代之的是,可以使用Java(用于类)和Scala(用于类型)提供的反射API。 -在Scala 2.10中,不建议使用`scala.reflect.ClassManifest`,而推荐使用`TypeTag`和`ClassTag`,并且计划在即将发布的版本中弃用`scala.reflect.Manifest`。因此,建议迁移任何基于`Manifest`的API以使用`Tag`。 \ No newline at end of file +在Scala 2.10中,不建议使用`scala.reflect.ClassManifest`,而推荐使用`TypeTag`和`ClassTag`,并且计划在即将发布的版本中弃用`scala.reflect.Manifest`。因此,建议迁移任何基于`Manifest`的API以使用`Tag`。 diff --git a/_zh-cn/tour/annotations.md b/_zh-cn/tour/annotations.md index 8d340efe08..c69d1fbc1f 100644 --- a/_zh-cn/tour/annotations.md +++ b/_zh-cn/tour/annotations.md @@ -7,7 +7,7 @@ num: 30 language: zh-cn -next-page: default-parameter-values +next-page: packages-and-imports previous-page: by-name-parameters --- diff --git a/_zh-cn/tour/mixin-class-composition.md b/_zh-cn/tour/mixin-class-composition.md index f51354554c..1875e0ec58 100644 --- a/_zh-cn/tour/mixin-class-composition.md +++ b/_zh-cn/tour/mixin-class-composition.md @@ -30,7 +30,7 @@ println(d.message) // I'm an instance of class B println(d.loudMessage) // I'M AN INSTANCE OF CLASS B ``` -类`D`有一个父类`B`和一个混入`C`。一个类只能有一个父类但是可以有多个混入(分别使用关键字`extend`和`with`)。混入和某个父类可能有相同的父类。 +类`D`有一个父类`B`和一个混入`C`。一个类只能有一个父类但是可以有多个混入(分别使用关键字`extends`和`with`)。混入和某个父类可能有相同的父类。 现在,让我们看一个更有趣的例子,其中使用了抽象类: @@ -81,4 +81,4 @@ object StringIteratorTest extends App { } ``` -新的类`RichStringIter`有一个父类`StringIterator`和一个混入`RichIterator`。如果是单一继承,我们将不会达到这样的灵活性。 \ No newline at end of file +新的类`RichStringIter`有一个父类`StringIterator`和一个混入`RichIterator`。如果是单一继承,我们将不会达到这样的灵活性。 diff --git a/api/all.md b/api/all.md index 0ca4d83e28..0519ad1068 100644 --- a/api/all.md +++ b/api/all.md @@ -6,10 +6,10 @@ includeTOC: true ## Latest releases -* Scala 2.13.3 - * [Library API](https://www.scala-lang.org/api/2.13.3/) - * [Compiler API](https://www.scala-lang.org/api/2.13.3/scala-compiler/scala/) - * [Reflection API](https://www.scala-lang.org/api/2.13.3/scala-reflect/scala/reflect/) +* Scala 2.13.4 + * [Library API](https://www.scala-lang.org/api/2.13.4/) + * [Compiler API](https://www.scala-lang.org/api/2.13.4/scala-compiler/scala/) + * [Reflection API](https://www.scala-lang.org/api/2.13.4/scala-reflect/scala/reflect/) * Scala 2.12.12 * [Library API](https://www.scala-lang.org/api/2.12.12/) * [Compiler API](https://www.scala-lang.org/api/2.12.12/scala-compiler/scala/) @@ -53,6 +53,10 @@ includeTOC: true ## Previous releases +* Scala 2.13.3 + * [Library API](https://www.scala-lang.org/api/2.13.3/) + * [Compiler API](https://www.scala-lang.org/api/2.13.3/scala-compiler/scala/) + * [Reflection API](https://www.scala-lang.org/api/2.13.3/scala-reflect/scala/reflect/) * Scala 2.13.2 * [Library API](https://www.scala-lang.org/api/2.13.2/) * [Compiler API](https://www.scala-lang.org/api/2.13.2/scala-compiler/scala/)