diff --git a/Gemfile b/Gemfile index 896a75036c..9d6132e3af 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,6 @@ source 'https://rubygems.org' gem 'jekyll-redirect-from' -# gem 'html-proofer' # link-checking: bundle exec htmlproofer ./_site/ --only-4xx --empty-alt-ignore --allow-hash-href +gem 'html-proofer' # group :jekyll_plugins do # gem 'hawkins' diff --git a/Gemfile.lock b/Gemfile.lock index 122d727d68..28b2ebf785 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,11 +1,31 @@ GEM remote: https://rubygems.org/ specs: + activesupport (5.1.4) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (~> 0.7) + minitest (~> 5.1) + tzinfo (~> 1.1) addressable (2.5.1) public_suffix (~> 2.0, >= 2.0.2) colorator (1.1.0) + colorize (0.8.1) + concurrent-ruby (1.0.5) + ethon (0.11.0) + ffi (>= 1.3.0) ffi (1.9.18) forwardable-extended (2.6.0) + html-proofer (3.7.5) + activesupport (>= 4.2, < 6.0) + addressable (~> 2.3) + colorize (~> 0.8) + mercenary (~> 0.3.2) + nokogiri (~> 1.7) + parallel (~> 1.3) + typhoeus (~> 0.7) + yell (~> 2.0) + i18n (0.9.1) + concurrent-ruby (~> 1.0) jekyll (3.5.1) addressable (~> 2.4) colorator (~> 1.0) @@ -29,6 +49,11 @@ GEM rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) mercenary (0.3.6) + mini_portile2 (2.3.0) + minitest (5.10.3) + nokogiri (1.8.1) + mini_portile2 (~> 2.3.0) + parallel (1.12.0) pathutil (0.14.0) forwardable-extended (~> 2.6) public_suffix (2.0.5) @@ -42,12 +67,19 @@ GEM sass-listen (4.0.0) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) + thread_safe (0.3.6) + typhoeus (0.8.0) + ethon (>= 0.8.0) + tzinfo (1.2.4) + thread_safe (~> 0.1) + yell (2.0.7) PLATFORMS ruby DEPENDENCIES + html-proofer jekyll-redirect-from BUNDLED WITH - 1.15.4 + 1.16.0 diff --git a/_ba/tour/automatic-closures.md b/_ba/tour/automatic-closures.md new file mode 100644 index 0000000000..dc6e83de40 --- /dev/null +++ b/_ba/tour/automatic-closures.md @@ -0,0 +1,10 @@ +--- +layout: tour +title: Automatic Type-Dependent Closure Construction + +discourse: false + +partof: scala-tour + +language: ba +--- diff --git a/_ba/tour/tour-of-scala.md b/_ba/tour/tour-of-scala.md index 3e7505955b..fd506be132 100644 --- a/_ba/tour/tour-of-scala.md +++ b/_ba/tour/tour-of-scala.md @@ -20,26 +20,26 @@ Scala elegantno objedinjuje mogućnosti objektno orijentisanih i funkcionalnih j ## Scala je objektno orijentisana ## Scala je čisto objektno orijentisan jezik u smislu da je [svaka vrijednost objekt](unified-types.html). Tipovi i ponašanja objekata se opisuju kroz [klase](classes.html) i [trejtove](traits.html). -Klase se proširuju nasljeđivanjem i fleksibilnim mehanizmom [kompozicije mixina](mixin-class-composition.html) +Klase se proširuju nasljeđivanjem i fleksibilnim mehanizmom [kompozicije mixina](mixin-class-composition.html) kao čistom zamjenom za višestruko nasljeđivanje. ## Scala je funkcionalna ## Scala je također funkcionalni jezik u smislu da je [svaka funkcija vrijednost](unified-types.html). -Scala ima [lahku sintaksu](anonymous-function-syntax.html) za definisanje anonimnih funkcija, +Scala ima lahku sintaksu za definisanje anonimnih funkcija, i podržava [funkcije višeg reda](higher-order-functions.html), omogućuje [ugnježdavanje funkcija](nested-functions.html), i podržava [curry-jevanje](currying.html). Scaline [case klase](case-classes.html) i njen mehanizam [podudaranja uzoraka](pattern-matching.html) modeluju algebarske tipove koji se koriste u dosta funkcionalnih programskih jezika. [Singlton objekti](singleton-objects.html) omogućuju pogodan način za grupisanje funkcija koje nisu članovi klase. -Nadalje, Scalin mehanizam podudaranja uzoraka (pattern-matching) prirodno podržava [procesiranje XML podataka](xml-processing.html) -pomoću [desno-ignorišućih uzoraka sekvenci](regular-expression-patterns.html), +Nadalje, Scalin mehanizam podudaranja uzoraka (pattern-matching) prirodno podržava procesiranje XML podataka +pomoću [desno-ignorišućih uzoraka sekvenci](regular-expression-patterns.html), i generalnim proširivanjem s [ekstraktor objektima](extractor-objects.html). -U ovom kontekstu, [komprehensije sekvenci](sequence-comprehensions.html) su korisne za izražavanje upita (query). +U ovom kontekstu, komprehensije sekvenci su korisne za izražavanje upita (query). Ove mogućnosti čine Scalu idealnom za razvijanje aplikacija kao što su web servisi. ## Scala je statički tipizirana (statically typed) ## -Scala je opremljena ekspresivnim sistemom tipova koji primorava da se apstrakcije koriste na bezbjedan i smislen način. +Scala je opremljena ekspresivnim sistemom tipova koji primorava da se apstrakcije koriste na bezbjedan i smislen način. Konkretno, sistem tipova podržava sljedeće: * [generičke klase](generic-classes.html) @@ -47,12 +47,12 @@ Konkretno, sistem tipova podržava sljedeće: * [gornje](upper-type-bounds.html) i [donje](lower-type-bounds.html) granice tipa, * [unutarnje klase](inner-classes.html) i [apstraktne tipove](abstract-types.html) kao članove objekta * [složene tipove](compound-types.html) -* [eksplicitno tipizirane samo-reference](explicitly-typed-self-references.html) +* [eksplicitno tipizirane samo-reference](self-types.html) * implicitne [parametre](implicit-parameters.html) i [konverzije](implicit-conversions.html) * [polimorfne metode](polymorphic-methods.html) Mehanizam za [lokalno zaključivanje tipova](local-type-inference.html) se brine da korisnik ne mora pisati tipove varijabli -više nego što je potrebno. +više nego što je potrebno. U kombinaciji, ove mogućnosti su jaka podloga za bezbjedno ponovno iskorištenje programskih apstrakcija i za tipski bezbjedno proširenje softvera. @@ -65,10 +65,10 @@ jezičkih konstrukcija u formi biblioteka. Zajedničkom upotrebom obje mogućnosti olakšava definisanje novih izraza bez proširenja sintakse samog Scala jezika i bez korištenja olakšica u vidu macro-a ili meta-programiranja. -Scala je dizajnirana za interoperabilnost s popularnim Java Runtime Environment (JRE). -Konkretno, interakcija s popularnim objektno orijentisanim Java programskim jezikom je prirodna. +Scala je dizajnirana za interoperabilnost s popularnim Java Runtime Environment (JRE). +Konkretno, interakcija s popularnim objektno orijentisanim Java programskim jezikom je prirodna. Novije mogućnosti Jave kao [anotacije](annotations.html) i Javini generički tipovi imaju direktnu analogiju u Scali. -Scaline mogućnosti bez analogija u Javi, kao što su [podrazumijevani](default-parameter-values.html) i [imenovani parametri](named-parameters.html), +Scaline mogućnosti bez analogija u Javi, kao što su [podrazumijevani](default-parameter-values.html) i [imenovani parametri](named-arguments.html), se kompajliraju što približnije Javi. Scala ima isti kompilacijski model (posebno kompajliranje, dinamičko učitavanje klasa) kao Java i time omogućuje pristupanje hiljadama postojećih visoko kvalitetnih biblioteka. diff --git a/_books/2-scala-for-the-impatient.md b/_books/2-scala-for-the-impatient.md index 1113269218..41e63d0c1d 100644 --- a/_books/2-scala-for-the-impatient.md +++ b/_books/2-scala-for-the-impatient.md @@ -5,7 +5,6 @@ image: /resources/img/books/scala_for_the_impatient.png status: Available Now authors: ["Cay S. Horstmann"] publisher: Addison-Wesley -publisherLink: https://heuk.pearson.com/about-us.html/Addison-Wesley/ --- What you get: diff --git a/_es/overviews/parallel-collections/concrete-parallel-collections.md b/_es/overviews/parallel-collections/concrete-parallel-collections.md index f8c65f1e3b..158c923f6e 100644 --- a/_es/overviews/parallel-collections/concrete-parallel-collections.md +++ b/_es/overviews/parallel-collections/concrete-parallel-collections.md @@ -24,7 +24,7 @@ Una secuencia [ParArray](http://www.scala-lang.org/api/{{ site.scala-version }}/ scala> pa map (x => (x - 1) / 2) res1: scala.collection.parallel.mutable.ParArray[Int] = ParArray(0, 1, 2, 3, 4, 5, 6, 7,... -Internamente, para partir el array para que sea procesado de forma paralela se utilizan [splitters]({{ site.baseurl }}/es/overviews/parallel-collections/architecture.html#core_abstractions) (o "partidores"). El Splitter parte y crea dos nuevos splitters con sus índices actualizados. A continuación son utilizados los [combiners]({{ site.baseurl }}/es/overviews/parallel-collections/architecture.html#core_abstractions) (o "combinadores"), que necesitan un poco más de trabajo. Ya que en la mayoría de los métodos transformadores (ej: `flatMap`, `filter`, `takeWhile`, etc.) previamente no es sabido la cantidad de elementos (y por ende, el tamaño del array), cada combiner es esencialmente una variante de un array buffer con un tiempo constante de la operación `+=`. Diferentes procesadores añaden elementos a combiners de arrays separados, que después son combinados al encadenar sus arrays internos. El array subyacente se crea en memoria y se rellenan sus elementos después que el número total de elementos es conocido. Por esta razón, los métodos transformadores son un poco más caros que los métodos de acceso. También, nótese que la asignación de memoria final procede secuencialmente en la JVM, lo que representa un cuello de botella si la operación de mapeo (el método transformador aplicado) es en sí económico (en términos de procesamiento). +Internamente, para partir el array para que sea procesado de forma paralela se utilizan [splitters]({{ site.baseurl }}/es/overviews/parallel-collections/architecture.html) (o "partidores"). El Splitter parte y crea dos nuevos splitters con sus índices actualizados. A continuación son utilizados los [combiners]({{ site.baseurl }}/es/overviews/parallel-collections/architecture.html) (o "combinadores"), que necesitan un poco más de trabajo. Ya que en la mayoría de los métodos transformadores (ej: `flatMap`, `filter`, `takeWhile`, etc.) previamente no es sabido la cantidad de elementos (y por ende, el tamaño del array), cada combiner es esencialmente una variante de un array buffer con un tiempo constante de la operación `+=`. Diferentes procesadores añaden elementos a combiners de arrays separados, que después son combinados al encadenar sus arrays internos. El array subyacente se crea en memoria y se rellenan sus elementos después que el número total de elementos es conocido. Por esta razón, los métodos transformadores son un poco más caros que los métodos de acceso. También, nótese que la asignación de memoria final procede secuencialmente en la JVM, lo que representa un cuello de botella si la operación de mapeo (el método transformador aplicado) es en sí económico (en términos de procesamiento). Al invocar el método `seq`, los arrays paralelos son convertidos al tipo de colección `ArraySeq`, que vendría a ser la contraparte secuencial del `ParArray`. Esta conversión es eficiente, y el `ArraySeq` utiliza a bajo nivel el mismo array que había sido obtenido por el array paralelo. @@ -53,7 +53,7 @@ Un [ParRange](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/colle scala> 15 to 5 by -2 par res1: scala.collection.parallel.immutable.ParRange = ParRange(15, 13, 11, 9, 7, 5) -Tal como los rangos secuenciales no tienen constructores, los rangos paralelos no tienen [combiner]({{ site.baseurl }}/overviews/parallel-collections/architecture.html#core_abstractions)s. Mapear elementos de un rango paralelo produce un vector paralelo. Los rangos secuenciales y paralelos pueden ser convertidos de uno a otro utilizando los métodos `seq` y `par`. +Tal como los rangos secuenciales no tienen constructores, los rangos paralelos no tienen [combiner]({{ site.baseurl }}/overviews/parallel-collections/architecture.html)s. Mapear elementos de un rango paralelo produce un vector paralelo. Los rangos secuenciales y paralelos pueden ser convertidos de uno a otro utilizando los métodos `seq` y `par`. scala> (1 to 5 par) map ((x) => x * 2) res2: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(2, 4, 6, 8, 10) @@ -85,7 +85,7 @@ y scala> phs map { x => x * x } sum res0: Int = 332833500 -De forma similar a las tablas hash paralelas, los [combiners]({{ site.baseurl }}/overviews/parallel-collections/architecture.html#core_abstractions) de los hash tries paralelos pre-ordenan los elementos en posiciones y construyen el hash trie resultante en paralelo al asignarle distintos grupos de posiciones a diferentes procesadores, los cuales contruyen los sub-tries independientemente. +De forma similar a las tablas hash paralelas, los [combiners]({{ site.baseurl }}/overviews/parallel-collections/architecture.html) de los hash tries paralelos pre-ordenan los elementos en posiciones y construyen el hash trie resultante en paralelo al asignarle distintos grupos de posiciones a diferentes procesadores, los cuales contruyen los sub-tries independientemente. Los hash tries paralelos pueden ser convertidos hacia y desde hash tries secuenciales por medio de los métodos `seq` y `par`. @@ -114,7 +114,7 @@ Un [concurrent.TrieMap](http://www.scala-lang.org/api/{{ site.scala-version }}/s ... -Para ofrecer más detalles de lo que sucede bajo la superficie, los [Combiners]({{ site.baseurl }}/overviews/parallel-collections/architecture.html#core_abstractions) son implementados como `TrieMap`s --ya que esta es una estructura de datos concurrente, solo un combiner es construido para todo la invocación al método transformador y compartido por todos los procesadores. +Para ofrecer más detalles de lo que sucede bajo la superficie, los [Combiners]({{ site.baseurl }}/overviews/parallel-collections/architecture.html) son implementados como `TrieMap`s --ya que esta es una estructura de datos concurrente, solo un combiner es construido para todo la invocación al método transformador y compartido por todos los procesadores. Al igual que todas las colecciones paralelas mutables, `TrieMap`s y la versión paralela, `ParTrieMap`s obtenidas mediante los métodos `seq` o `par` subyacentemente comparten la misma estructura de almacenamiento, por lo tanto modificaciones en una es visible en la otra. diff --git a/_es/overviews/parallel-collections/overview.md b/_es/overviews/parallel-collections/overview.md index b5f13762f2..8e69d27b2a 100644 --- a/_es/overviews/parallel-collections/overview.md +++ b/_es/overviews/parallel-collections/overview.md @@ -53,7 +53,7 @@ executed in parallel. De forma de ilustrar la generalidad y utilidad de las colecciones paralelizadas, proveemos un conjunto de ejemplos de uso útiles, todos ellos siendo ejecutados en paralelo de forma totalmente transparente al usuario. -_Nota:_ Algunos de los siguientes ejemplos operan en colecciones pequeñas, lo cual no es recomendado. Son provistos como ejemplo para ilustrar solamente el propósito. Como una regla heurística general, los incrementos en velocidad de ejecución comienzan a ser notados cuando el tamaño de la colección es lo suficientemente grande, tipicamente algunos cuantos miles de elementos. (Para más información en la relación entre tamaño de una coleccion paralelizada y su performance, por favor véase [appropriate subsection]({{ site.baseurl}}/es/overviews/parallel-collections/performance.html#how_big_should_a_collection_be_to_go_parallel) en la sección [performance]({{ site.baseurl }}/es/overviews/parallel-collections/performance.html) (en inglés). +_Nota:_ Algunos de los siguientes ejemplos operan en colecciones pequeñas, lo cual no es recomendado. Son provistos como ejemplo para ilustrar solamente el propósito. Como una regla heurística general, los incrementos en velocidad de ejecución comienzan a ser notados cuando el tamaño de la colección es lo suficientemente grande, tipicamente algunos cuantos miles de elementos. (Para más información en la relación entre tamaño de una coleccion paralelizada y su performance, por favor véase [appropriate subsection]({{ site.baseurl}}/es/overviews/parallel-collections/performance.html) en la sección [performance]({{ site.baseurl }}/es/overviews/parallel-collections/performance.html) (en inglés). #### map @@ -195,5 +195,4 @@ _Nota:_ Generalmente se piensa que, al igual que las operaciones no asociativas, Lo que implica el "fuera de orden" en las colecciones paralelizadas es solamente que la operación será ejecutada fuera de orden (en un sentido _temporal_, es decir no secuencial, no significa que el resultado va a ser re-"*combinado*" fuera de orden (en un sentido de _espacio_). Al contrario, en general los resultados siempre serán reensamblados en roden, es decir una colección paralelizada que se divide en las siguientes particiones A, B, C, en ese orden, será reensamblada nuevamente en el orden A, B, C. No en otro orden arbitrario como B, C, A. -Para más información de cómo se dividen y se combinan los diferentes tipos de colecciones paralelizadas véase el artículo sobre [Arquitectura]({{ site.baseurl }}/es/overviews -/parallel-collections/architecture.html) de esta misma serie. +Para más información de cómo se dividen y se combinan los diferentes tipos de colecciones paralelizadas véase el artículo sobre [Arquitectura]({{ site.baseurl }}/es/overviews/parallel-collections/architecture.html) de esta misma serie. diff --git a/_es/tour/annotations.md b/_es/tour/annotations.md index 2f9dea008d..490e2287da 100644 --- a/_es/tour/annotations.md +++ b/_es/tour/annotations.md @@ -36,7 +36,7 @@ El significado de las anotaciones _depende de la implementación_. En la platafo En el siguiente ejemplo agregamos la anotación `throws` a la definición del método `read` de manera de capturar la excepción lanzada en el programa principal de Java. -> El compilador de Java comprueba que un programa contenga manejadores para [excepciones comprobadas](http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html) al analizar cuales de esas excepciones comprobadas pueden llegar a lanzarse en la ejecución de un método o un constructor. Por cada excepción comprobada que sea un posible resultado, la cláusula **throws** debe para ese método o constructor debe ser mencionada en la clase de esa excepción o una de las superclases. +> El compilador de Java comprueba que un programa contenga manejadores para excepciones comprobadas al analizar cuales de esas excepciones comprobadas pueden llegar a lanzarse en la ejecución de un método o un constructor. Por cada excepción comprobada que sea un posible resultado, la cláusula **throws** debe para ese método o constructor debe ser mencionada en la clase de esa excepción o una de las superclases. > Ya que Scala no tiene excepciones comprobadas, los métodos en Scala deben ser anotados con una o más anotaciones `throws` para que el código Java pueda capturar las excepciones lanzadas por un método de Scala. package examples diff --git a/_es/tour/anonymous-function-syntax.md b/_es/tour/anonymous-function-syntax.md deleted file mode 100644 index 9801b51b6a..0000000000 --- a/_es/tour/anonymous-function-syntax.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -layout: tour -title: Sintaxis de funciones anónimas - -discourse: false - -partof: scala-tour - -num: 14 -language: es - -next-page: currying -previous-page: nested-functions ---- - -Scala provee una sintaxis relativamente livana para definir funciones anónimas. La siguiente expresión crea una función incrementadora para números enteros: - - (x: Int) => x + 1 - -El código anterior es una forma compacta para la definición de la siguiente clase anónima: - - new Function1[Int, Int] { - def apply(x: Int): Int = x + 1 - } - -También es posible definir funciones con múltiples parámetros: - - (x: Int, y: Int) => "(" + x + ", " + y + ")" - -o sin parámetros: - - () => { System.getProperty("user.dir") } - -Existe también una forma simple para escribir los tipos de las funciones. A continuación se muestran los tipos de las trés funciones escritas anteriormente: - - Int => Int - (Int, Int) => String - () => String - -La sintaxis anterior es la forma sintética de escribir los siguientes tipos: - - Function1[Int, Int] - Function2[Int, Int, String] - Function0[String] diff --git a/_es/tour/basics.md b/_es/tour/basics.md new file mode 100644 index 0000000000..bd86428a9b --- /dev/null +++ b/_es/tour/basics.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: Basics + +discourse: false + +partof: scala-tour +language: es +--- diff --git a/_es/tour/by-name-parameters.md b/_es/tour/by-name-parameters.md new file mode 100644 index 0000000000..da953ddcb4 --- /dev/null +++ b/_es/tour/by-name-parameters.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: By-name Parameters + +discourse: false + +partof: scala-tour +language: es +--- diff --git a/_es/tour/compound-types.md b/_es/tour/compound-types.md index c9f43d3eee..a60e7b54b5 100644 --- a/_es/tour/compound-types.md +++ b/_es/tour/compound-types.md @@ -9,7 +9,7 @@ partof: scala-tour num: 6 language: es -next-page: sequence-comprehensions +next-page: extractor-objects previous-page: case-classes --- diff --git a/_es/tour/currying.md b/_es/tour/currying.md index 1e0fdac05e..9eff54f5b1 100644 --- a/_es/tour/currying.md +++ b/_es/tour/currying.md @@ -10,7 +10,7 @@ num: 15 language: es next-page: automatic-closures -previous-page: anonymous-function-syntax +previous-page: nested-functions --- _Nota de traducción: Currying es una técnica de programación funcional nombrada en honor al matemático y lógico Haskell Curry. Es por eso que no se intentará hacer ninguna traducción sobre el término Currying. Entiendase este como una acción, técnica base de PF. Como una nota al paso, el lenguaje de programación Haskell debe su nombre a este eximio matemático._ diff --git a/_es/tour/default-parameter-values.md b/_es/tour/default-parameter-values.md index eb4b70911d..4a34538fce 100644 --- a/_es/tour/default-parameter-values.md +++ b/_es/tour/default-parameter-values.md @@ -9,7 +9,7 @@ partof: scala-tour num: 34 language: es -next-page: named-parameters +next-page: named-arguments previous-page: implicit-conversions --- @@ -66,4 +66,4 @@ Scala cuenta con soporte directo para esto: // mediante parametros nombrados val m4 = new HashMap[String,Int](loadFactor = 0.8) -Nótese cómo podemos sacar ventaja de cualquier valor por defecto al utilizar [parámetros nombrados]({{ site.baseurl }}/tutorials/tour/named-parameters.html). +Nótese cómo podemos sacar ventaja de cualquier valor por defecto al utilizar [parámetros nombrados]({{ site.baseurl }}/tutorials/tour/named-arguments.html). diff --git a/_es/tour/extractor-objects.md b/_es/tour/extractor-objects.md index 9278a2e276..5f1d180488 100644 --- a/_es/tour/extractor-objects.md +++ b/_es/tour/extractor-objects.md @@ -10,7 +10,7 @@ num: 8 language: es next-page: generic-classes -previous-page: sequence-comprehensions +previous-page: compound-types --- En Scala pueden ser definidos patrones independientemente de las clases Caso (en inglés case classes, desde ahora clases Case). Para este fin exite un método llamado `unapply` que proveera el ya dicho extractor. Por ejemplo, en el código siguiente se define el objeto extractor `Twice` diff --git a/_es/tour/for-comprehensions.md b/_es/tour/for-comprehensions.md new file mode 100644 index 0000000000..55903d9f1b --- /dev/null +++ b/_es/tour/for-comprehensions.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: For Comprehensions + +discourse: false + +partof: scala-tour +language: es +--- diff --git a/_es/tour/local-type-inference.md b/_es/tour/local-type-inference.md index b236ca118a..0bbf7400fa 100644 --- a/_es/tour/local-type-inference.md +++ b/_es/tour/local-type-inference.md @@ -10,7 +10,7 @@ num: 29 language: es next-page: unified-types -previous-page: explicitly-typed-self-references +previous-page: self-types --- Scala tiene incorporado un mecanismo de inferencia de tipos el cual permite al programador omitir ciertos tipos de anotaciones. Por ejemplo, generalmente no es necesario especificar el tipo de una variable, ya que el compilador puede deducir el tipo mediante la expresión de inicialización de la variable. También puede generalmente omitirse los tipos de retorno de métodos ya que se corresponden con el tipo del cuerpo, que es inferido por el compilador. diff --git a/_es/tour/lower-type-bounds.md b/_es/tour/lower-type-bounds.md index 0819ecde6f..0fc3b5aba5 100644 --- a/_es/tour/lower-type-bounds.md +++ b/_es/tour/lower-type-bounds.md @@ -9,7 +9,7 @@ partof: scala-tour num: 26 language: es -next-page: explicitly-typed-self-references +next-page: self-types previous-page: upper-type-bounds --- diff --git a/_es/tour/named-parameters.md b/_es/tour/named-arguments.md similarity index 78% rename from _es/tour/named-parameters.md rename to _es/tour/named-arguments.md index 6ecb8c877d..ab289648a7 100644 --- a/_es/tour/named-parameters.md +++ b/_es/tour/named-arguments.md @@ -25,7 +25,7 @@ En la invocación de métodos y funciones se puede usar el nombre de las variabl imprimirNombre(last = "Smith",first = "John") // Imprime "John Smith" -Note que una vez que se utilizan parámetros nombrados en la llamada, el orden no importa, mientras todos los parámetros sean nombrados. Esta característica funciona bien en conjunción con [valores de parámetros por defecto]({{ site.baseurl }}/tutorials/tour/default_parameter_values.html): +Note que una vez que se utilizan parámetros nombrados en la llamada, el orden no importa, mientras todos los parámetros sean nombrados. Esta característica funciona bien en conjunción con valores de parámetros por defecto: def imprimirNombre(nombre:String = "John", apellido:String = "Smith") = { println(nombre + " " + apellido) @@ -34,4 +34,5 @@ Note que una vez que se utilizan parámetros nombrados en la llamada, el orden n printName(apellido = "Jones") // Imprime "John Jones" -Ya que es posible colocar los parámetros en cualquier orden que te guste, puedes usar el valor por defecto para parámetros que aparecen primero en la lista de parámetros. +language: es +--- diff --git a/_es/tour/nested-functions.md b/_es/tour/nested-functions.md index c592b30c65..01f706872d 100644 --- a/_es/tour/nested-functions.md +++ b/_es/tour/nested-functions.md @@ -9,7 +9,7 @@ partof: scala-tour num: 13 language: es -next-page: anonymous-function-syntax +next-page: currying previous-page: singleton-objects --- diff --git a/_es/tour/explicitly-typed-self-references.md b/_es/tour/self-types.md similarity index 100% rename from _es/tour/explicitly-typed-self-references.md rename to _es/tour/self-types.md diff --git a/_es/tour/sequence-comprehensions.md b/_es/tour/sequence-comprehensions.md deleted file mode 100644 index 203a01b4c8..0000000000 --- a/_es/tour/sequence-comprehensions.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -layout: tour -title: Sequencias por Comprensión - -discourse: false - -partof: scala-tour - -num: 7 -language: es - -next-page: extractor-objects -previous-page: compound-types ---- - -Scala cuenta con una notación ligera para expresar *sequencias por comprensión* (*sequence comprehensions*). Las comprensiones tienen la forma `for (enumeradores) yield e`, donde `enumeradores` se refiere a una lista de enumeradores separados por el símbolo punto y coma (;). Un *enumerador* puede ser tanto un generador el cual introduce nuevas variables, o un filtro. La comprensión evalúa el cuerpo `e` por cada paso (o ciclo) generado por los enumeradores y retorna una secuencia de estos valores. - -Aquí hay un ejemplo: - - object ComprehensionTest1 extends App { - def pares(desde: Int, hasta: Int): List[Int] = - for (i <- List.range(desde, hasta) if i % 2 == 0) yield i - Console.println(pares(0, 20)) - } - -La expresión `for` en la función introduce una nueva variable `i` de tipo `Int` la cual es subsecuentemente atada a todos los valores de la lista `List(desde, desde + 1, ..., hasta - 1)`. La guarda `if i % 2 == 0` filtra los números impares por lo que el cuerpo (que solo consiste de la expresión `i`) es solamente evaluado para números pares. Consecuentemente toda la expresión `for` retorna una lista de números pares. - -El programa produce los siguientes valores - - List(0, 2, 4, 6, 8, 10, 12, 14, 16, 18) - -Aquí se muestra un ejemplo más complicado que computa todos los pares de números entre `0` y `n-1` cuya suma es igual a un número dado `v`: - - object ComprehensionTest2 extends App { - def foo(n: Int, v: Int) = - for (i <- 0 until n; - j <- i until n if i + j == v) yield - Pair(i, j); - foo(20, 32) foreach { - case (i, j) => - println("(" + i + ", " + j + ")") - } - } - -Este ejemplo muestra que las comprensiones no están restringidas solo a listas. El programa anterior usa iteradores en su lugar. Cualquier tipo de datos que soporte las operaciones `withFilter`, `map`, y `flatMap` (con los tipos apropiados) puede ser usado en la comprensión de secuencias. - -Esta es la salida del programa: - - (13, 19) - (14, 18) - (15, 17) - (16, 16) - -Existe también una forma especial de comprensión de secuencias la cual retorna `Unit`. En este caso las variables que son creadas por la lista de generadores y filtros son usados para realizar tareas con efectos colaterales (modificaciones de algún tipo). El programador tiene que omitir la palabra reservada `yield` para usar una comprensión de este tipo. - - object ComprehensionTest3 extends App { - for (i <- Iterator.range(0, 20); - j <- Iterator.range(i, 20) if i + j == 32) - println("(" + i + ", " + j + ")") - } diff --git a/_es/tour/tour-of-scala.md b/_es/tour/tour-of-scala.md index ba2fe0eeaf..5c3caa3956 100644 --- a/_es/tour/tour-of-scala.md +++ b/_es/tour/tour-of-scala.md @@ -15,12 +15,12 @@ next-page: abstract-types Scala es un lenguaje de programación moderno multi-paradigma diseñado para expresar patrones de programación comunes de una forma concisa, elegante, y de tipado seguro. Integra fácilmente características de lenguajes orientados a objetos y funcionales. ## Scala es orientado a objetos ## -Scala es un lenguaje puramente orientado a objetos en el sentido de que [todo es un objeto](unified_types.html). Los tipos y comportamientos de objetos son descritos por [clases](classes.html) y [traits](traits.html) (que podría ser traducido como un "rasgo"). Las clases pueden ser extendidas a través de subclases y un mecanismo flexible [de composición mezclada](mixin-class-composition.html) que provee un claro remplazo a la herencia múltiple. +Scala es un lenguaje puramente orientado a objetos en el sentido de que todo es un objeto. Los tipos y comportamientos de objetos son descritos por [clases](classes.html) y [traits](traits.html) (que podría ser traducido como un "rasgo"). Las clases pueden ser extendidas a través de subclases y un mecanismo flexible [de composición mezclada](mixin-class-composition.html) que provee un claro remplazo a la herencia múltiple. ## Scala es funcional ## -Scala es también un lenguaje funcional en el sentido que [toda función es un valor](unified_types.html). Scala provee una [sintaxis ligera](anonymous-function-syntax.html) para definir funciones anónimas. Soporta [funciones de primer orden](higher-order-functions.html), permite que las funciones sean [anidadas](nested-functions.html), y soporta [currying](currying.html). Las [clases caso](case-classes.html) de Scala y las construcciones incorporadas al lenguaje para [reconocimiento de patrones](pattern-matching.html) modelan tipos algebráicos usados en muchos lenguajes de programación funcionales. +Scala es también un lenguaje funcional en el sentido que toda función es un valor. Scala provee una sintaxis ligera para definir funciones anónimas. Soporta [funciones de primer orden](higher-order-functions.html), permite que las funciones sean [anidadas](nested-functions.html), y soporta [currying](currying.html). Las [clases caso](case-classes.html) de Scala y las construcciones incorporadas al lenguaje para [reconocimiento de patrones](pattern-matching.html) modelan tipos algebráicos usados en muchos lenguajes de programación funcionales. -Además, la noción de reconocimiento de patrones de Scala se puede extender naturalmente al [procesamiento de datos XML](xml-processing.html) con la ayuda de [patrones de expresiones regulares](regular-expression-patterns.html). En este contexto, [seq comprehensions](sequence-comprehensions.html) resultan útiles para formular consultas. Estas características hacen a Scala ideal para desarrollar aplicaciones como Web Services. +Además, la noción de reconocimiento de patrones de Scala se puede extender naturalmente al procesamiento de datos XML con la ayuda de [patrones de expresiones regulares](regular-expression-patterns.html). En este contexto, seq comprehensions resultan útiles para formular consultas. Estas características hacen a Scala ideal para desarrollar aplicaciones como Web Services. ## Scala estáticamente tipado ## Scala cuenta con un expresivo sistema de tipado que fuerza estáticamente las abstracciones a ser usadas en una manera coherente y segura. En particular, el sistema de tipado soporta: @@ -29,7 +29,7 @@ Scala cuenta con un expresivo sistema de tipado que fuerza estáticamente las ab * límites de tipado [superiores](upper-type-bounds.html) e [inferiores](lower-type-bounds.html), * [clases internas](inner-classes.html) y [tipos abstractos](abstract-types.html) como miembros de objetos, * [tipos compuestos](compound-types.html) -* [auto-referencias explicitamente tipadas](explicitly-typed-self-references.html) +* [auto-referencias explicitamente tipadas](self-types.html) * [implicit conversions](implicit-conversions.html) * [métodos polimórficos](polymorphic-methods.html) diff --git a/_ja/overviews/collections/concrete-mutable-collection-classes.md b/_ja/overviews/collections/concrete-mutable-collection-classes.md index 3af7780441..4889c7a559 100644 --- a/_ja/overviews/collections/concrete-mutable-collection-classes.md +++ b/_ja/overviews/collections/concrete-mutable-collection-classes.md @@ -92,7 +92,7 @@ Scala は不変キューの他に可変キュー ([`mutable.Queue`](http://www.s 既に不変スタックについては説明した。スタックには、[`mutable.Stack`](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/mutable/Stack.html) クラスにより実装される可変バージョンもある。変更が上書き処理されるという違いの他は、不変バージョンと全く同じように動作する。 - scala> val stack = new scala.collection.mutable.Stack[Int] + scala> val stack = new scala.collection.mutable.Stack[Int] stack: scala.collection.mutable.Stack[Int] = Stack() scala> stack.push(1) res0: stack.type = Stack(1) @@ -106,9 +106,9 @@ Scala は不変キューの他に可変キュー ([`mutable.Queue`](http://www.s res8: Int = 2 scala> stack res9: scala.collection.mutable.Stack[Int] = Stack(1, 2) - scala> stack.pop + scala> stack.pop res10: Int = 2 - scala> stack + scala> stack res11: scala.collection.mutable.Stack[Int] = Stack(1) ## 配列スタック @@ -140,7 +140,7 @@ Scala は不変キューの他に可変キュー ([`mutable.Queue`](http://www.s ## 並行マップ -並行マップ ([`ConcurrentMap`](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/mutable/ConcurrentMap.html)) は複数のスレッドから同時にアクセスすることできる。通常の[マップ](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/Map.html)の演算の他に、以下のアトミックな演算を提供する: +並行マップ (`ConcurrentMap`) は複数のスレッドから同時にアクセスすることできる。通常の[マップ](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/Map.html)の演算の他に、以下のアトミックな演算を提供する: ### ConcurrentMap クラスの演算 ### @@ -151,7 +151,7 @@ Scala は不変キューの他に可変キュー ([`mutable.Queue`](http://www.s | `m replace (k, old, new)`|`k` に関連付けられた値が `old` である場合、それを `new` で上書きする。| | `m replace (k, v)` |`k` に任意の関連付けられた値がある場合、それを `v` で上書きする。| -[`ConcurrentMap`](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/mutable/ConcurrentMap.html) は Scala コレクションライブラリ内のトレイトだ。現在そのトレイトを実装するのは Java の +`ConcurrentMap` は Scala コレクションライブラリ内のトレイトだ。現在そのトレイトを実装するのは Java の `java.util.concurrent.ConcurrentMap` クラスだけで、それは [Java/Scala コレクションの標準変換](conversions-between-java-and-scala-collections.html)を使って Scala のマップに変換することができる。 ## 可変ビット集合 diff --git a/_ja/overviews/collections/seqs.md b/_ja/overviews/collections/seqs.md index 3f9156e2d7..ba414a79bc 100644 --- a/_ja/overviews/collections/seqs.md +++ b/_ja/overviews/collections/seqs.md @@ -83,7 +83,7 @@ Scala の他の構文の例にならって、`seq(idx) = elem` は `seq.update(i `Vector` は添字付き列と線形列の間の興味深い折衷案だ。 事実上定数時間のオーバーヘッドで添字アクセスと線形アクセスを提供するからだ。 そのため、ベクトルは添字アクセスと線形アクセスの両方を混合して使用してるアクセスパターンにおける良い基盤となる。 -ベクトルに関しては、また[後ほど詳しくみていく](concrete-immutable-collection-classes.html#vectors)。 +ベクトルに関しては、また[後ほど詳しくみていく](concrete-immutable-collection-classes.html)。 ### バッファ ### diff --git a/_ja/overviews/collections/sets.md b/_ja/overviews/collections/sets.md index d84225e5c0..679c9641ea 100644 --- a/_ja/overviews/collections/sets.md +++ b/_ja/overviews/collections/sets.md @@ -107,7 +107,7 @@ language: ja 可変集合は `+=` と `-=` の別形として `add` と `remove` を提供する。違いは `add` と `remove` は集合に対して演算の効果があったかどうかを示す `Boolean` の戻り値を返すことだ。 -現在の可変集合のデフォルトの実装では要素を格納するのにハッシュテーブルを使っている。不変集合のデフォルトの実装は集合の要素数に応じて方法を変えている。空集合はシングルトンで表される。サイズが4つまでの集合は全要素をフィールドとして持つオブジェクトとして表される。それを超えたサイズの不変集合は[ハッシュトライ](#hash-tries)として表される。 +現在の可変集合のデフォルトの実装では要素を格納するのにハッシュテーブルを使っている。不変集合のデフォルトの実装は集合の要素数に応じて方法を変えている。空集合はシングルトンで表される。サイズが4つまでの集合は全要素をフィールドとして持つオブジェクトとして表される。それを超えたサイズの不変集合は[ハッシュトライ]()として表される。 このような設計方針のため、(例えば 4以下の) 小さいサイズの集合を使う場合は、通常の場合、可変集合に比べて不変集合の方が、よりコンパクトで効率的だ。集合のサイズが小さいと思われる場合は、不変集合を試してみてはいかがだろうか。 diff --git a/_ja/overviews/collections/trait-iterable.md b/_ja/overviews/collections/trait-iterable.md index 96d986e9f7..49fdf4cfbe 100644 --- a/_ja/overviews/collections/trait-iterable.md +++ b/_ja/overviews/collections/trait-iterable.md @@ -61,7 +61,7 @@ language: ja | **比較演算:**    | | | `xs sameElements ys` |`xs` と `ys` が同じ要素を同じ順序で格納しているかを調べる。| -継承階層では `Iterable` 直下に [`Seq`](https://www.scala-lang.org/api/current/scala/collection/Seq.html)、[`Set`](https://www.scala-lang.org/api/current/scala/collection/Set.html)、[`Map`](https://www.scala-lang.org/api/current/scala/collection/Map.html``) という三つのトレイトがある。 +継承階層では `Iterable` 直下に [`Seq`](https://www.scala-lang.org/api/current/scala/collection/Seq.html)、[`Set`](https://www.scala-lang.org/api/current/scala/collection/Set.html)、[`Map`](https://www.scala-lang.org/api/current/scala/collection/Map.html) という三つのトレイトがある。 この三つのトレイトに共通することは `apply` メソッドと `isDefinedAt` メソッドを持ったトレイト [` PartialFunction`](https://www.scala-lang.org/api/current/scala/PartialFunction.html) を実装しているということだ。 しかし、`PartialFunction` の実装方法は三者三様である。 diff --git a/_ja/overviews/index.md b/_ja/overviews/index.md index c0ac69f5ce..af6c8c2f2a 100644 --- a/_ja/overviews/index.md +++ b/_ja/overviews/index.md @@ -57,7 +57,7 @@ title: ガイドと概要 * [ユースケース](/ja/overviews/macros/usecases.html) * [blackbox vs whitebox](/ja/overviews/macros/blackbox-whitebox.html) * [def マクロ](/ja/overviews/macros/overview.html) - * [準クォート](/ja/overviews/quasiquotes/intro.html) + * 準クォート * [マクロバンドル](/ja/overviews/macros/bundles.html) * [implicit マクロ](/ja/overviews/macros/implicits.html) * [抽出子マクロ](/ja/overviews/macros/extractors.html) diff --git a/_ja/overviews/macros/blackbox-whitebox.md b/_ja/overviews/macros/blackbox-whitebox.md index 148fb846d8..13dcfcd921 100644 --- a/_ja/overviews/macros/blackbox-whitebox.md +++ b/_ja/overviews/macros/blackbox-whitebox.md @@ -35,7 +35,7 @@ Scala 2.11.x および Scala 2.12.x 系列では、マクロ機能が blackbox しかし、ときとして def マクロは「ただのメソッド呼び出し」という概念を超越することがある。例えば、展開されたマクロは、元のマクロの戻り値の型よりも特化された型を持つ式を返すことが可能だ。Scala 2.10 では、StackOverflow の [Static return type of Scala macros](http://stackoverflow.com/questions/13669974/static-return-type-of-scala-macros) で解説したように、そのような展開は特化された型を保持し続けることができる。 -この興味深い機能がもたらす柔軟性によって、[偽装型プロバイダ](http://meta.plasm.us/posts/2013/07/11/fake-type-providers-part-2/)、[具現化の拡張](/sips/pending/source-locations.html)、[関数従属性の具現化](/ja/overviews/macros/implicits.html#fundep_materialization)、[抽出子マクロ](https://github.com/paulp/scala/commit/84a335916556cb0fe939d1c51f27d80d9cf980dc)などを可能とするけども、書かれたコードの明確さ (人にとってもマシンにとっても) が犠牲になるという側面がある。 +この興味深い機能がもたらす柔軟性によって、[偽装型プロバイダ](http://meta.plasm.us/posts/2013/07/11/fake-type-providers-part-2/)、[具現化の拡張](/sips/source-locations.html)、[関数従属性の具現化](/ja/overviews/macros/implicits.html#fundep_materialization)、抽出子マクロなどを可能とするけども、書かれたコードの明確さ (人にとってもマシンにとっても) が犠牲になるという側面がある。 普通のメソッド同様に振る舞うマクロと戻り値の型を細別化 (refine) するマクロという決定的な区別を明確にするために、blackbox マクロと whitebox マクロという概念を導入することにした。型シグネチャに忠実に従うマクロは、振る舞いを理解するのに実装を知る必要が無い (ブラックボックスとして扱うことができる) ため、**blackbox マクロ** (blackbox macro) と呼ぶ。 Scala の型システムを使ってシグネチャを持つことができないマクロは **whitebox マクロ** (whitebox macro) と呼ぶ。(whitebox def マクロもシグネチャは持つが、これらのシグネチャは近似値でしかない) @@ -52,7 +52,7 @@ blackbox def マクロは Scala 2.10 の def マクロと異なる扱いとな 1. blackbox マクロが構文木 `x` に展開するとき、展開される式は型注釈 `(x: T)` でラップされる。この `T` は blackbox マクロの宣言された戻り値の型に、マクロ適用時に一貫性を持つように型引数やパス依存性を適用したものとなる。これによって、blackbox マクロを[型プロバイダ](http://meta.plasm.us/posts/2013/07/11/fake-type-providers-part-2/)のための手段としての利用は無効となる。 1. Scala の型推論アルゴリズムが終わった後でも blackbox マクロの適用に未決定の型パラメータが残る場合、これらの型パラメータは普通のメソッドと同様に強制的に型推論が実行される。これによって blackbox マクロから型推論に影響を与えることが不可能となり、[関数従属性の具現化](/ja/overviews/macros/implicits.html#fundep_materialization)に使うことが無効となる。 -1. blackbox マクロの適用が implicit の候補として使われる場合、implicit 検索がそのマクロを選択するまでは展開は実行されない。これによって [implicit マクロの入手可能性を動的に計算する](/sips/pending/source-locations.html)ことが無効となる。 -1. blackbox マクロの適用がパターンマッチの抽出子として使われる場合、無条件でコンパイラエラーを発生するようにして、マクロで実装された[パターンマッチングのカスタマイズ](https://github.com/paulp/scala/commit/84a335916556cb0fe939d1c51f27d80d9cf980dc)を無効となる。 +1. blackbox マクロの適用が implicit の候補として使われる場合、implicit 検索がそのマクロを選択するまでは展開は実行されない。これによって [implicit マクロの入手可能性を動的に計算する](/sips/source-locations.html)ことが無効となる。 +1. blackbox マクロの適用がパターンマッチの抽出子として使われる場合、無条件でコンパイラエラーを発生するようにして、マクロで実装されたパターンマッチングのカスタマイズを無効となる。 whitebox def マクロは Scala 2.10 での def マクロ同様に動作する。一切の制限が無いため、2.10 のマクロで出来ていたことの全てが 2.11 と 2.12 でも行えるはずだ。 diff --git a/_ja/overviews/macros/roadmap.md b/_ja/overviews/macros/roadmap.md index 978f893d2b..4a8c7d471d 100644 --- a/_ja/overviews/macros/roadmap.md +++ b/_ja/overviews/macros/roadmap.md @@ -32,7 +32,7 @@ title: ロードマップ | [implicit マクロ](/ja/overviews/macros/implicits.html) | Yes (since 2.10.2) | Yes 1 | Yes | Yes 1 | Yes | Yes 1 | | [関数従属性の具現化](/ja/overviews/macros/implicits.html#fundep_materialization) | No | Yes 2 | Yes | Yes 1 | Yes | Yes 1 | | [型プロバイダ](/ja/overviews/macros/typeproviders.html) | 一部サポート (see docs) | Yes 2 | 一部サポート (see docs) | Yes 2 | 一部サポート (see docs) | Yes 2 | -| [準クォート](/ja/overviews/quasiquotes/intro.html) | No | Yes 1 | Yes | Yes 1 | Yes | Yes 1 | +| 準クォート | No | Yes 1 | Yes | Yes 1 | Yes | Yes 1 | | [型マクロ](/ja/overviews/macros/typemacros.html) | No | No | No | No | No | No | | [型指定の無いマクロ](/ja/overviews/macros/untypedmacros.html) | No | No | No | No | No | No | | [マクロアノテーション](/ja/overviews/macros/annotations.html) | No | Yes 2 | No | Yes 2 | No | Yes 2 | diff --git a/_ja/overviews/macros/typemacros.md b/_ja/overviews/macros/typemacros.md index d7ecd103b9..8a99b8d47e 100644 --- a/_ja/overviews/macros/typemacros.md +++ b/_ja/overviews/macros/typemacros.md @@ -26,7 +26,7 @@ def マクロがコンパイラが特定をメソッドの呼び出しを見つ Db.Coffees.update(brazilian.copy(price = 10)) println(Db.Coffees.all) -`H2Db` マクロの完全なソースコードは [GitHub にて](https://github.com/xeno-by/typemacros-h2db)提供して、本稿では重要な点だけをかいつまんで説明する。まず、マクロは、コンパイル時にデータベースに接続することで静的に型付けされたデータベースのラッパーを生成する。(構文木の生成に関しては[リフレクションの概要](http://docs.scala-lang.org/ja/overviews/reflection/overview.html)にて説明する) 次に、NEW `c.introduceTopLevel` API ([Scaladoc](https://scala-webapps.epfl.ch/jenkins/view/misc/job/macro-paradise211-nightly-main/ws/dists/latest/doc/scala-devel-docs/api/index.html#scala.reflect.macros.Synthetics)) を用いて生成されたラッパーをコンパイラによって管理されているトップレベル定義のリストに挿入する。最後に、マクロは生成されたクラスのスーパーコンストラクタを呼び出す `Apply` ノードを返す。注意 `c.Expr[T]` に展開される def マクロとちがって型マクロは `c.Tree` に展開されることに注意してほしい。これは、`Expr` が値を表すのに対して、型マクロは型に展開することによる。 +`H2Db` マクロの完全なソースコードは [GitHub にて](https://github.com/xeno-by/typemacros-h2db)提供して、本稿では重要な点だけをかいつまんで説明する。まず、マクロは、コンパイル時にデータベースに接続することで静的に型付けされたデータベースのラッパーを生成する。(構文木の生成に関しては[リフレクションの概要](http://docs.scala-lang.org/ja/overviews/reflection/overview.html)にて説明する) 次に、NEW `c.introduceTopLevel` API を用いて生成されたラッパーをコンパイラによって管理されているトップレベル定義のリストに挿入する。最後に、マクロは生成されたクラスのスーパーコンストラクタを呼び出す `Apply` ノードを返す。注意 `c.Expr[T]` に展開される def マクロとちがって型マクロは `c.Tree` に展開されることに注意してほしい。これは、`Expr` が値を表すのに対して、型マクロは型に展開することによる。 type H2Db(url: String) = macro impl @@ -76,7 +76,7 @@ def マクロがコンパイラが特定をメソッドの呼び出しを見つ -Scala のプログラムにおいて型マクロは、type、applied type、parent type、new、そして annotation という 5つ役割 (role) のうちの 1つとして登場する。マクロが使われた役割によって許される展開は異なっている。また、役割は NEW `c.macroRole` API ([Scaladoc](https://scala-webapps.epfl.ch/jenkins/view/misc/job/macro-paradise211-nightly-main/ws/dists/latest/doc/scala-devel-docs/api/index.html#scala.reflect.macros.Enclosures)) によって検査することができる。 +Scala のプログラムにおいて型マクロは、type、applied type、parent type、new、そして annotation という 5つ役割 (role) のうちの 1つとして登場する。マクロが使われた役割によって許される展開は異なっている。また、役割は NEW `c.macroRole` API によって検査することができる。 @@ -99,4 +99,4 @@ Scala のプログラムにおいて型マクロは、type、applied type、pare ### クラスやオブジェクトの生成 -[StackOverflow](http://stackoverflow.com/questions/13795490/how-to-use-type-calculated-in-scala-macro-in-a-reify-clause) でも説明したが、型マクロを作っていると `reify` がどんどん役に立たなくなっていくことに気付くだろう。その場合は、手で構文木を構築するだけではなく、マクロパラダイスにあるもう1つの実験的機能である[準クォート](/ja/overviews/quasiquotes/intro.html)を使うことも検討してみてほしい。 +[StackOverflow](http://stackoverflow.com/questions/13795490/how-to-use-type-calculated-in-scala-macro-in-a-reify-clause) でも説明したが、型マクロを作っていると `reify` がどんどん役に立たなくなっていくことに気付くだろう。その場合は、手で構文木を構築するだけではなく、マクロパラダイスにあるもう1つの実験的機能である準クォートを使うことも検討してみてほしい。 diff --git a/_ja/overviews/macros/untypedmacros.md b/_ja/overviews/macros/untypedmacros.md index d8ae597381..7bd68cfa82 100644 --- a/_ja/overviews/macros/untypedmacros.md +++ b/_ja/overviews/macros/untypedmacros.md @@ -52,7 +52,7 @@ title: 型指定の無いマクロ 型指定の無いマクロは抽出子マクロを可能とすることに注意してほしい: [SI-5903](https://issues.scala-lang.org/browse/SI-5903)。 Scala 2.10.x においても `unapply` や `unaoolySeq` をマクロとして宣言することは可能だが、リンクした JIRA ケースに記述されているとおり、使い勝手は非常に制限されたものとなっている。パターンマッチング内におけるテキスト抽象化の全力は型指定の無いマクロによって発揮できるようになる。 -詳細は単体テストの [test/files/run/macro-expand-unapply-c](https://github.com/scalamacros/kepler/tree/paradise/macros/test/files/run/macro-expand-unapply-c) を参照。 +詳細は単体テストの test/files/run/macro-expand-unapply-c を参照。 もしマクロに型指定の無いパラメータがあった場合、マクロ展開を型付けする際にタイプチェッカーは引数に関しては何もせずに型指定の無いままマクロに渡す。もしいくつかのパラメータが型アノテーションを持っていたとしても、現行では無視される。これは将来改善される予定だ: [SI-6971](https://issues.scala-lang.org/browse/SI-6971)。引数が型検査されていないため、implicit の解決や型引数の推論は実行されない (しかし、両者ともそれぞれ `c.typeCheck` と `c.inferImplicitValue` として実行できる)。 @@ -62,4 +62,4 @@ Scala 2.10.x においても `unapply` や `unaoolySeq` をマクロとして宣 最後に、型指定のないマクロのパッチは `c.Expr[T]` の代わりにマクロ実装のシグネチャのどこでも `c.Tree` を使うことを可能とする。 マクロ定義の型指定なし/型付きと、構文木/式によるマクロ実装の 4通りの組み合わせ全てがパラメータと戻り値の型の両方においてサポートされている。 -さらに詳しいことはユニットテストを参照してほしい: [test/files/run/macro-untyped-conformance](https://github.com/scalamacros/kepler/blob/b55bda4860a205c88e9ae27015cf2d6563cc241d/test/files/run/macro-untyped-conformance/Impls_Macros_1.scala)。 +さらに詳しいことはユニットテストを参照してほしい: test/files/run/macro-untyped-conformance。 diff --git a/_ja/overviews/parallel-collections/concrete-parallel-collections.md b/_ja/overviews/parallel-collections/concrete-parallel-collections.md index e7d7f98eca..1681cfa468 100644 --- a/_ja/overviews/parallel-collections/concrete-parallel-collections.md +++ b/_ja/overviews/parallel-collections/concrete-parallel-collections.md @@ -27,8 +27,8 @@ language: ja scala> pa map (x => (x - 1) / 2) res1: scala.collection.parallel.mutable.ParArray[Int] = ParArray(0, 1, 2, 3, 4, 5, 6, 7,... -内部的には、並列配列の[「スプリッタ」 (splitter)](architecture.html#id1) の分割は走査用の添字を更新した二つの新たなスプリッタを作る事に結局なる。 -[「コンバイナ」 (combiner)](architecture.html#id1) はより複雑だ。多くの変換メソッドの多く(例えば、`flatMap`、`filter`、`takeWhile` など)は、事前に結果の要素数(そのため、配列のサイズ)が分からないため、それぞれのコンバイナはならし定数時間 (amortized constant time) の +内部的には、並列配列の[「スプリッタ」 (splitter)](architecture.html) の分割は走査用の添字を更新した二つの新たなスプリッタを作る事に結局なる。 +[「コンバイナ」 (combiner)](architecture.html) はより複雑だ。多くの変換メソッドの多く(例えば、`flatMap`、`filter`、`takeWhile` など)は、事前に結果の要素数(そのため、配列のサイズ)が分からないため、それぞれのコンバイナはならし定数時間 (amortized constant time) の `+=` 演算を持つ配列バッファの変種だ。 異なるプロセッサがそれぞれの並列配列コンバイナに要素を追加し、後で内部の配列を連結することで合成が行われる。 要素の総数が分かった後になってから、内部の配列が割り当てられ、並列に書き込まれる。そのため、変換メソッドは読み込みメソッドに比べて少し高価だ。また、最後の配列の割り当ては JVM上で逐次的に実行されるため、map 演算そのものが非常に安価な場合は、配列の割り当てが逐次的ボトルネックとなりうる。 diff --git a/_ja/overviews/parallel-collections/overview.md b/_ja/overviews/parallel-collections/overview.md index d4360d200c..c9bf8e5f57 100644 --- a/_ja/overviews/parallel-collections/overview.md +++ b/_ja/overviews/parallel-collections/overview.md @@ -55,7 +55,7 @@ Scala の並列コレクションライブラリは、順次ライブラリコ 並列コレクションの一般性と利便性を例示するために、いくつかの簡単な具体例を用いて説明しよう。全ての例において、ユーザが意識すること無く演算は並列に実行されている。 **注意:** 以下の例ではサイズの小さいコレクションを並列化しているが、これはあくまで説明のための例で、実用では推奨されない。 -一般的な指標として、コレクションのサイズが数千要素など、サイズが大きいほど並列化による高速化が顕著であることが多い。(並列コレクションのサイズと性能に関する詳細に関しては、このガイドの[性能](performance.html)に関する節の[該当する項](performance.html#id18)を参照してほしい) +一般的な指標として、コレクションのサイズが数千要素など、サイズが大きいほど並列化による高速化が顕著であることが多い。(並列コレクションのサイズと性能に関する詳細に関しては、このガイドの[性能](performance.html)に関する節の[該当する項](performance.html)を参照してほしい) #### map @@ -117,13 +117,13 @@ Scala の並列コレクションライブラリは、順次ライブラリコ sum: Int = 0 scala> list.foreach(sum += _); sum - res02: Int = 457073 + res02: Int = 457073 scala> var sum = 0 sum: Int = 0 scala> list.foreach(sum += _); sum - res03: Int = 468520 + res03: Int = 468520 ここでは、`sum` が 0 に初期化されて、`list` に対して `foreach` が呼び出されるたびに `sum` が異なる値を持っていることが分かる。この非決定性の原因は**データ競合** (data race; 同一の可変変数に対する並行した読み書き) だ。 diff --git a/_ja/overviews/reflection/overview.md b/_ja/overviews/reflection/overview.md index 432b9f696f..004a43795b 100644 --- a/_ja/overviews/reflection/overview.md +++ b/_ja/overviews/reflection/overview.md @@ -97,7 +97,7 @@ Scala コンパイラが持つ型情報を全ては入手できない可能性 #### ランタイム型のインスタンス化 リフレクションによって得られた型は適当な invoker ミラーを使ってコンストラクタを呼び出すことでインスタンス化することができる -(ミラーに関しては[後ほど]({{ site.baseurl }}/ja/overviews/reflection/overview.html#mirrors)説明する)。 +(ミラーに関しては[後ほど]({{ site.baseurl }}/ja/overviews/reflection/overview.html)説明する)。 以下に REPL を使った具体例を用いて説明しよう: scala> case class Person(name: String) @@ -132,7 +132,7 @@ Scala コンパイラが持つ型情報を全ては入手できない可能性 #### ランタイム型のメンバへのアクセスと呼び出し 一般的に、ランタイム型のメンバは適当な invoker ミラーを使ってコンストラクタを呼び出すことでインスタンス化することができる -(ミラーに関しては[後ほど]({{ site.baseurl }}/ja/overviews/reflection/overview.html#mirrors)説明する)。 +(ミラーに関しては[後ほど]({{ site.baseurl }}/ja/overviews/reflection/overview.html)説明する)。 以下に REPL を使った具体例を用いて説明しよう: scala> case class Purchase(name: String, orderNumber: Int, var shipped: Boolean) @@ -282,7 +282,7 @@ API に基づいていることだ。これにより、マクロと実行時リ ユニバースは、型 (`Type`)、構文木 (`Tree`)、アノテーション (`Annotation`) といったリフレクションで使われる主要な概念に対するインターフェイスを提供する。 詳細はこのガイドの[ユニバース]({{ site.baseurl}}/ja/overviews/reflection/environment-universes-mirrors.html)の節か、 -`scala.reflect.api` パッケージの[ユニバースの API doc](http://www.scala-lang.org/api/{{ site.scala-version}}/scala/reflect/api/Universe.html) +`scala.reflect.api` パッケージのユニバースの API doc を参考にしてほしい。 このガイドにおける多くの例を含め、Scala リフレクションを利用するには何らかの @@ -299,5 +299,5 @@ API に基づいていることだ。これにより、マクロと実行時リ 型情報の種類やリフレクションを用いたタスクの種類によって異なるミラーを使う必要がある。 詳細はこのガイドの[ミラー]({{ site.baseurl}}/ja/overviews/reflection/environment-universes-mirrors.html)の節か、 -`scala.reflect.api` パッケージの[ミラーの API doc](http://www.scala-lang.org/api/{{ site.scala-version}}/scala/reflect/api/Mirrors.html) +`scala.reflect.api` パッケージのミラーの API doc を参考にしてほしい。 diff --git a/_ja/overviews/reflection/symbols-trees-types.md b/_ja/overviews/reflection/symbols-trees-types.md index 360c5615f2..a2b01ce5e0 100644 --- a/_ja/overviews/reflection/symbols-trees-types.md +++ b/_ja/overviews/reflection/symbols-trees-types.md @@ -39,7 +39,7 @@ title: シンボル、構文木、型 `NoSymbol` という特殊なシングルトン・オブジェクトのオーナーが用いられる。 シンボルが無いことを表す `NoSymbol` は空を表わしたり、デフォルトの値として API の中で多用されている。 `NoSymbol` の `owner` にアクセスすると例外が発生する。 -[`Symbol`](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/reflect/api/Symbols$SymbolApi.html) +`Symbol` 型によって提供される一般インターフェイスに関しては API doc を参照してほしい。 ### 型シンボル (`TypeSymbol`) @@ -123,7 +123,7 @@ title: シンボル、構文木、型 res0: scala.reflect.runtime.universe.Type = scala.List[Int] この例では、型コンストラクタ `List` に型引数 `Int` が適用された -[`scala.reflect.api.Types$TypeRef`](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/reflect/api/Types$TypeRef.html) +`scala.reflect.api.Types$TypeRef` が返っている。 しかし、この方法はインスタンス化しようとしている型を手動で指定する必要があることに注意してほしい。 @@ -358,9 +358,9 @@ Scala の数値型は以下の順序付けに従っている (Scala 言語仕様 Scala リフレクションで、構文木を生成または利用する API には以下のようなものがある: -1. Scala アノテーションは引数に構文木を用い、`Annotation.scalaArgs` として公開されている。(詳細はこのガイドの[アノテーション]({{ site.baseurl }}/ja/overviews/reflection/names-exprs-scopes-more.html)の節を参照) +1. Scala アノテーションは引数に構文木を用い、`Annotation.scalaArgs` として公開されている。(詳細はこのガイドのアノテーションの節を参照) 2. 任意の式を受け取りその AST を返す `reify` という特殊なメソッド。 -3. マクロを用いたコンパイル時リフレクション (詳細は[マクロ]({{ site.baseurl }}/ja/overview/macros/overview.html)参照) とツールボックスを用いた実行時リフレクションは両方とも構文木を用いてプログラムを表現する。 +3. マクロを用いたコンパイル時リフレクション (詳細はマクロ参照) とツールボックスを用いた実行時リフレクションは両方とも構文木を用いてプログラムを表現する。 ここで注意してほしいのは構文木は `pos` (`Position`)、 `symbol` (`Symbol`)、 と型検査の際に代入される `tpe` (`Type`) という 3つのフィールドの他は不変 (immutable) であることだ。 @@ -409,7 +409,7 @@ Scala リフレクションは、ユニバース経由で構文木を視覚化 expr: scala.reflect.runtime.universe.Expr[Unit] = ... ここで、`reify` は Scala 式を受け取り `Tree` と `TypeTag` をラッピングする `Expr` を返す。 -(`Expr` の詳細に関してはこのガイドの[式]({{ site.baseurl }}/ja/overviews/reflection/names-exprs-scopes-more.html)の節を参照) +(`Expr` の詳細に関してはこのガイドの式の節を参照) `expr` が保持する構文木は以下のように取得できる: scala> val tree = expr.tree diff --git a/_ko/tour/annotations.md b/_ko/tour/annotations.md index a846ddf373..4e2cba3524 100644 --- a/_ko/tour/annotations.md +++ b/_ko/tour/annotations.md @@ -36,7 +36,7 @@ previous-page: automatic-closures 다음 예제에선 자바의 메인 프로그램에서 던지는 예외를 잡기 위해, `read` 메소드에 `throws` 어노테이션을 추가했다. -> 자바 컴파일러는 메소드나 생성자를 실행할 때 어떤 확인 예외가 발생할 수 있는지 분석해, 프로그램이 [확인이 필요한 예외](http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html)를 처리할 핸들러를 포함하고 있는지 검사한다. 메소드나 생성자의 **throws** 절에선 발생할 가능성이 있는 확인 예외마다, 해당 예외의 클래스나 해당 예외 클래스의 상위 클래스를 반드시 명시해야 한다. +> 자바 컴파일러는 메소드나 생성자를 실행할 때 어떤 확인 예외가 발생할 수 있는지 분석해, 프로그램이 확인이 필요한 예외를 처리할 핸들러를 포함하고 있는지 검사한다. 메소드나 생성자의 **throws** 절에선 발생할 가능성이 있는 확인 예외마다, 해당 예외의 클래스나 해당 예외 클래스의 상위 클래스를 반드시 명시해야 한다. > 스칼라는 확인 예외가 없기 때문에 스칼라 메소드는 스칼라 메소드가 던지는 예외를 자바 코드가 잡을 수 있도록 반드시 하나 이상의 `throws` 어노테이션을 붙여야 한다. package examples diff --git a/_ko/tour/anonymous-function-syntax.md b/_ko/tour/anonymous-function-syntax.md deleted file mode 100644 index 7e6fb5dd42..0000000000 --- a/_ko/tour/anonymous-function-syntax.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -layout: tour -title: 익명 함수 구문 - -discourse: false - -partof: scala-tour - -num: 6 -language: ko - -next-page: higher-order-functions -previous-page: mixin-class-composition ---- - -스칼라를 사용하면 비교적 간결한 구문을 통해 익명 함수를 정의할 수 있다. 다음 표현식은 정수의 지정 함수를 만들어준다. - - (x: Int) => x + 1 - -이는 다음의 익명 클래스 정의를 축약한 표현이다. - - new Function1[Int, Int] { - def apply(x: Int): Int = x + 1 - } - -마찬가지로 여러 파라미터의 함수를 정의하거나: - - (x: Int, y: Int) => "(" + x + ", " + y + ")" - -파라미터가 없는 함수를 정의할 수도 있다: - - () => { System.getProperty("user.dir") } - -매우 간결하게 함수 타입을 작성하는 방법도 있다. 다음은 위에서 정의한 세 함수의 타입이다. - - Int => Int - (Int, Int) => String - () => String - -이 구문은 다음 타입을 축약한 표현이다. - - Function1[Int, Int] - Function2[Int, Int, String] - Function0[String] - -윤창석, 이한욱 옮김 \ No newline at end of file diff --git a/_ko/tour/basics.md b/_ko/tour/basics.md new file mode 100644 index 0000000000..82f3816b90 --- /dev/null +++ b/_ko/tour/basics.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: Basics + +discourse: false + +partof: scala-tour +language: ko +--- diff --git a/_ko/tour/by-name-parameters.md b/_ko/tour/by-name-parameters.md new file mode 100644 index 0000000000..b4202656cd --- /dev/null +++ b/_ko/tour/by-name-parameters.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: By-name Parameters + +discourse: false + +partof: scala-tour +language: ko +--- diff --git a/_ko/tour/compound-types.md b/_ko/tour/compound-types.md index 218d27713d..d69fa52ac7 100644 --- a/_ko/tour/compound-types.md +++ b/_ko/tour/compound-types.md @@ -9,7 +9,7 @@ partof: scala-tour num: 23 language: ko -next-page: explicitly-typed-self-references +next-page: self-types previous-page: abstract-types --- diff --git a/_ko/tour/default-parameter-values.md b/_ko/tour/default-parameter-values.md index 7917647f68..983bc60d8f 100644 --- a/_ko/tour/default-parameter-values.md +++ b/_ko/tour/default-parameter-values.md @@ -9,7 +9,7 @@ partof: scala-tour num: 32 language: ko -next-page: named-parameters +next-page: named-arguments previous-page: annotations --- @@ -61,6 +61,6 @@ previous-page: annotations // 이름을 지정한 인수를 통해 로드 팩터만을 오버라이드 val m4 = new HashMap[String,Int](loadFactor = 0.8) -*모든* 기본 값에 [이름을 지정한 파라미터]({{ site.baseurl }}/tutorials/tour/named-parameters.html)를 활용할 수 있음을 기억하자. +*모든* 기본 값에 [이름을 지정한 파라미터]({{ site.baseurl }}/tutorials/tour/named-arguments.html)를 활용할 수 있음을 기억하자. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/extractor-objects.md b/_ko/tour/extractor-objects.md index f72bf933f7..fee7ae08c9 100644 --- a/_ko/tour/extractor-objects.md +++ b/_ko/tour/extractor-objects.md @@ -9,7 +9,7 @@ partof: scala-tour num: 15 language: ko -next-page: sequence-comprehensions +next-page: generic-classes previous-page: regular-expression-patterns --- @@ -19,7 +19,7 @@ previous-page: regular-expression-patterns def apply(x: Int): Int = x * 2 def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None } - + object TwiceTest extends App { val x = Twice(21) x match { case Twice(n) => Console.println(n) } // prints 21 diff --git a/_ko/tour/for-comprehensions.md b/_ko/tour/for-comprehensions.md new file mode 100644 index 0000000000..d414c1c8f6 --- /dev/null +++ b/_ko/tour/for-comprehensions.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: For Comprehensions + +discourse: false + +partof: scala-tour +language: ko +--- diff --git a/_ko/tour/generic-classes.md b/_ko/tour/generic-classes.md index 66d27163e2..fbca0a9dc4 100644 --- a/_ko/tour/generic-classes.md +++ b/_ko/tour/generic-classes.md @@ -10,7 +10,7 @@ num: 17 language: ko next-page: variances -previous-page: sequence-comprehensions +previous-page: extractor-objects --- 자바 5(다른 이름은 [JDK 1.5](http://java.sun.com/j2se/1.5/))와 같이, 스칼라는 타입으로 파라미터화된 클래스의 빌트인 지원을 제공한다. 이런 제네릭 클래스는 특히 컬렉션 클래스의 개발에 유용하다. 이에 관한 예제를 살펴보자. @@ -42,4 +42,4 @@ previous-page: sequence-comprehensions _주의: 제네릭 클래스의 서브타입은 *불가변*이다. 즉, 캐릭터 타입의 스택인 `Stack[Char]`를 정수형 스택인 `Stack[Int]`처럼 사용할 수는 없다. 실제로 캐릭터 스택에는 정수가 들어가기 때문에 이런 제약은 이상하게 보일 수도 있다. 결론적으로 `S = T`일 때만 `Stack[T]`가 `Stack[S]`의 서브타입일 수 있으며, 반대의 관계도 마찬가지로 성립해야 한다. 이런 특징이 상당히 큰 제약일 수 있기 때문에, 스칼라는 제네릭 타입의 서브타입을 지정하는 행위를 제어하기 위해 [타입 파라미터 어노테이션 방법](variances.html)을 제공한다._ -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/higher-order-functions.md b/_ko/tour/higher-order-functions.md index fc05e4b802..40adfba248 100644 --- a/_ko/tour/higher-order-functions.md +++ b/_ko/tour/higher-order-functions.md @@ -10,7 +10,7 @@ num: 7 language: ko next-page: nested-functions -previous-page: anonymous-function-syntax +previous-page: mixin-class-composition --- 스칼라는 고차 함수의 정의를 허용한다. 이런 함수는 _다른 함수를 파라미터로 받거나_, 수행의 _결과가 함수다_. 다음과 같은 함수 `apply`는 다른 함수 `f`와 값 `v`를 받아서 함수 `f`를 `v`에 적용한다. @@ -20,21 +20,21 @@ previous-page: anonymous-function-syntax _주의: 문맥적으로 함수가 필요하다면, 메소드는 자동으로 이에 맞게 강제된다._ 다음은 또 다른 예제다. - + class Decorator(left: String, right: String) { def layout[A](x: A) = left + x.toString() + right } - + object FunTest extends App { def apply(f: Int => String, v: Int) = f(v) val decorator = new Decorator("[", "]") println(apply(decorator.layout, 7)) } - + 실행 결과는 다음과 같다. [7] 이 예제에서 메소드 `decorator.layout`은 메소드 `apply`에서 요구하는 바와 같이 타입 `Int => String`의 값으로 자동 강제된다. 메소드 `decorator.layout`이 _다형성 메소드_(즉, 자신의 서명 타입 중 일부를 추상화하는)이고, 스칼라 컴파일러는 가장 적합한 메소드 타입을 인스턴스화 해야만 한다는 점을 명심하자. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/implicit-parameters.md b/_ko/tour/implicit-parameters.md index 8132d96ad6..4c8a7bf4cf 100644 --- a/_ko/tour/implicit-parameters.md +++ b/_ko/tour/implicit-parameters.md @@ -10,7 +10,7 @@ num: 25 language: ko next-page: implicit-conversions -previous-page: explicitly-typed-self-references +previous-page: self-types --- _암시적 파라미터_ 를 갖는 메서드 역시 다른 일반적인 메서드와 마찬가지로 인수를 적용할 수 있다. 이런 경우 implicit 키워드는 아무런 영향을 미치지 않는다. 하지만, 이 경우에 암시적 파라미터에 주는 인수를 생략한다면, 그 생략된 인수는 자동적으로 제공될 것이다. diff --git a/_ko/tour/mixin-class-composition.md b/_ko/tour/mixin-class-composition.md index 8b0d14720b..a054152adc 100644 --- a/_ko/tour/mixin-class-composition.md +++ b/_ko/tour/mixin-class-composition.md @@ -9,7 +9,7 @@ partof: scala-tour num: 5 language: ko -next-page: anonymous-function-syntax +next-page: higher-order-functions previous-page: traits --- @@ -22,22 +22,22 @@ _단일 상속_ 만을 지원하는 여러 언어와는 달리, 스칼라는 더 } 이어서, 이터레이터가 반환하는 모든 항목에 주어진 함수를 적용해주는 `foreach` 메소드로 `AbsIterator`를 확장한 믹스인 클래스를 살펴보자. 믹스인으로 사용할 수 있는 클래스를 정의하기 위해선 `trait`이란 키워드를 사용한다. - + trait RichIterator extends AbsIterator { def foreach(f: T => Unit) { while (hasNext) f(next()) } } - + 다음은 주어진 문자열의 캐릭터를 차례로 반환해주는 콘크리트 이터레이터 클래스다. - + class StringIterator(s: String) extends AbsIterator { type T = Char private var i = 0 def hasNext = i < s.length() def next() = { val ch = s charAt i; i += 1; ch } } - + `StringIterator`와 `RichIterator`를 하나의 클래스로 합치고 싶다면 어떻게 할까. 두 클래스 모두는 코드가 포함된 멤버 구현을 담고 있기 때문에 단일 상속과 인터페이스 만으론 불가능한 일이다. 스칼라는 _믹스인 클래스 컴포지션_ 으로 이런 상황을 해결해준다. 프로그래머는 이를 사용해 클래스 정의에서 변경된 부분을 재사용할 수 있다. 이 기법은 주어진 문자열에 포함된 모든 캐릭터를 한 줄로 출력해주는 다음의 테스트 프로그램에서와 같이, `StringIterator`와 `RichIterator`를 통합할 수 있도록 해준다. - + object StringIteratorTest { def main(args: Array[String]) { class Iter extends StringIterator("Scala") with RichIterator @@ -45,7 +45,7 @@ _단일 상속_ 만을 지원하는 여러 언어와는 달리, 스칼라는 더 iter foreach println } } - + `main` 함수의 `Iter` 클래스는 부모인 `StringIterator`와 `RichIterator`를 `with` 키워드를 사용해 믹스인 컴포지션해서 만들어졌다. 첫 번째 부모를 `Iter`의 _슈퍼클래스_ 라고 부르며, 두 번째 부모를(더 이어지는 항목이 있다면 이 모두를 일컬어) _믹스인_ 이라고 한다. 윤창석, 이한욱 옮김 diff --git a/_ko/tour/named-parameters.md b/_ko/tour/named-arguments.md similarity index 100% rename from _ko/tour/named-parameters.md rename to _ko/tour/named-arguments.md diff --git a/_ko/tour/explicitly-typed-self-references.md b/_ko/tour/self-types.md similarity index 100% rename from _ko/tour/explicitly-typed-self-references.md rename to _ko/tour/self-types.md diff --git a/_ko/tour/sequence-comprehensions.md b/_ko/tour/sequence-comprehensions.md deleted file mode 100644 index 3e64c37169..0000000000 --- a/_ko/tour/sequence-comprehensions.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -layout: tour -title: 시퀀스 컴프리헨션 - -discourse: false - -partof: scala-tour - -num: 16 -language: ko - -next-page: generic-classes -previous-page: extractor-objects ---- - -스칼라는 *시퀀스 컴프리헨션(sequence comprehensions)*을 표현하기 위한 간편한 문법을 제공한다. 컴프리헨션은 `for (enumerators) yield e`와 같은 형태를 가지며, 여기서 `enumerators`는 세미콜론으로 구분된 이뉴머레이터들을 뜻한다. *이뉴머레이터*는 새로운 변수를 정의하는 생성자이거나 필터이다. 컴프리헨션은 생성된 각각의 새로운 변수에 대해서 그 몸체인 `e`를 계산하여 그 값들의 시퀀스를 반환한다. - -예제 : - - object ComprehensionTest1 extends App { - def even(from: Int, to: Int): List[Int] = - for (i <- List.range(from, to) if i % 2 == 0) yield i - Console.println(even(0, 20)) - } - -위의 함수 안에 있는 for-구문은 `int` 타입의 변수 `i`를 정의하고 이어 `i`는 리스트 `List(from, from+1, ..., to - 1)`의 모든 값에 각각 대응된다. 가드 `if i % 2 == 0`는 홀수를 필터링하여 제외하여 (i만으로 이루어진) 몸체가 짝수에 대해서만 계산되도록 한다. 그 결과, 전체 for-구문은 짝수 리스트를 반환하게 된다. - -이 프로그램의 결과값은 다음과 같다 : - - List(0, 2, 4, 6, 8, 10, 12, 14, 16, 18) - -좀 더 복잡한 예제를 보자. 아래는 `0`과 `n-1`사이의 숫자로 이루어진 모든 순서쌍 중에서 그 합이 주어진 값 `v`와 같은 순서쌍을 계산하는 예제이다. - - object ComprehensionTest2 extends App { - def foo(n: Int, v: Int) = - for (i <- 0 until n; - j <- i until n if i + j == v) yield - (i, j); - foo(20, 32) foreach { - case (i, j) => - println(s"($i, $j)") - } - } - -이 예제는 컴프리헨션이 리스트에만 국한되지 않는다는 것을 보여준다. 리스트 대신에 이 프로그램에서는 이터레이터를 사용하였다. `withFilter`, `map`, `flatMap`기능을 지원하는 모든 데이터타입이 시퀀스 컴프리헨션에 이용될 수 있다. - -아래는 이 프로그램의 결과값이다: - - (13, 19) - (14, 18) - (15, 17) - (16, 16) - -시퀀스 컴프리헨션의 특별한 형태로 `Unit`을 반환하는 경우도 있다. (???어려워요. binding 뭐라고하지...) 이러한 시퀀스 익스프레션을 사용할 때에는 `yield` 키워드를 사용하지 않아야 한다. 아래 예제는 위의 예제와 같은 결과값을 출력하지만 `Unit`을 반환하는, 시퀀스 컴프리헨션의 특수형태를 사용하였다. - - object ComprehensionTest3 extends App { - for (i <- Iterator.range(0, 20); - j <- Iterator.range(i, 20) if i + j == 32) - println(s"($i, $j)") - } - -윤창석, 이한욱 옮김, 고광현 수정 diff --git a/_ko/tour/tour-of-scala.md b/_ko/tour/tour-of-scala.md index 6e2b1cfe56..66dbd5e0e0 100644 --- a/_ko/tour/tour-of-scala.md +++ b/_ko/tour/tour-of-scala.md @@ -18,9 +18,9 @@ next-page: unified-types [모든 값이 객체](unified-types.html)라는 측면에서 스칼라는 순수 객체지향 언어다. 객체의 타입과 행위는 [클래스](classes.html)와 [트레잇](traits.html)으로 나타난다. 클래스는 서브클래스를 만들거나, 다중 상속을 깔끔하게 대체하는 유연한 [믹스인 기반 컴포지션](mixin-class-composition.html) 방법을 통해 확장된다. ## 스칼라는 함수형이다 ## -또한, 스칼라는 [모든 함수가 값](unified-types.html)이라는 측면에서 함수형 언어다. 스칼라는 익명 함수를 위한 [경량 구문](anonymous-function-syntax.html)을 제공하고, [고차 함수](higher-order-functions.html)를 지원하며, 함수의 [중첩](nested-functions.html)을 허용하고, [커링](currying.html)을 지원한다. 스칼라의 [케이스 클래스](case-classes.html)와 케이스 클래스의 [패턴 매칭](pattern-matching.html) 빌트인 지원을 통해 여러 함수형 프로그래밍 언어에서 사용되는 대수 타입을 만들 수 있다. +또한, 스칼라는 [모든 함수가 값](unified-types.html)이라는 측면에서 함수형 언어다. 스칼라는 익명 함수를 위한 경량 구문을 제공하고, [고차 함수](higher-order-functions.html)를 지원하며, 함수의 [중첩](nested-functions.html)을 허용하고, [커링](currying.html)을 지원한다. 스칼라의 [케이스 클래스](case-classes.html)와 케이스 클래스의 [패턴 매칭](pattern-matching.html) 빌트인 지원을 통해 여러 함수형 프로그래밍 언어에서 사용되는 대수 타입을 만들 수 있다. -뿐만 아니라 스칼라의 패턴 매칭 개념은 [우측 무시 시퀀스 패턴](regular-expression-patterns.html)의 도움을 받아 자연스럽게 [XML 데이터의 처리](xml-processing.html)로 확장된다. 이런 맥락에서 [시퀀스 컴프리헨션](sequence-comprehensions.html)은 쿼리를 만들 때 유용하다. 이런 기능 때문에 스칼라는 웹 서비스와 같은 애플리케이션 개발에 있어서 이상적인 선택이 될 수 있다. +뿐만 아니라 스칼라의 패턴 매칭 개념은 [우측 무시 시퀀스 패턴](regular-expression-patterns.html)의 도움을 받아 자연스럽게 XML 데이터의 처리로 확장된다. 이런 맥락에서 시퀀스 컴프리헨션은 쿼리를 만들 때 유용하다. 이런 기능 때문에 스칼라는 웹 서비스와 같은 애플리케이션 개발에 있어서 이상적인 선택이 될 수 있다. ## 스칼라는 정적 타입이다 ## 스칼라는 안전하고 일관성 있는 추상화를 정적으로 강제하는 풍부한 타입 시스템을 장착하고 있다. 특히 타입 시스템은 다음과 같은 사항을 지원한다. @@ -28,10 +28,10 @@ next-page: unified-types * [제네릭 클래스](generic-classes.html) * [가변성 어노테이션](variances.html) * [상위 타입 경계](upper-type-bounds.html)와 [하위 타입 경계](lower-type-bounds.html) -* 객체 멤버로써의 [내부 클래스](inner-classes.html)와 [추상 타입](abstract-types.html) +* 객체 멤버로써의 [내부 클래스](inner-classes.html)와 [추상 타입](abstract-types.html) * [합성 타입](compound-types.html) -* [명시적으로 타입이 지정된 자기 참조](explicitly-typed-self-references.html) -* [뷰](views.html) +* [명시적으로 타입이 지정된 자기 참조](self-types.html) +* 뷰 * [다형 메소드](polymorphic-methods.html) [로컬 타입 추론 방식](local-type-inference.html)은 사용자가 불필요한 타입 정보를 어노테이션해야 하는 불편함을 줄여준다. 이와 함께, 이런 기능은 프로그래밍 추상화를 안전하게 재사용하고 소프트웨어를 타입 세이프하게 확장하는 강력한 기반이 된다. diff --git a/_overviews/collections/conversions-between-java-and-scala-collections.md b/_overviews/collections/conversions-between-java-and-scala-collections.md index 66e016c523..fb184cfac2 100644 --- a/_overviews/collections/conversions-between-java-and-scala-collections.md +++ b/_overviews/collections/conversions-between-java-and-scala-collections.md @@ -9,7 +9,7 @@ overview-name: Collections num: 17 -languages: [ja, zh-cn] +languages: [zh-cn] permalink: /overviews/collections/:title.html --- diff --git a/_overviews/collections/seqs.md b/_overviews/collections/seqs.md index 389fb3908e..3e12de6fc1 100644 --- a/_overviews/collections/seqs.md +++ b/_overviews/collections/seqs.md @@ -74,7 +74,7 @@ If a sequence is mutable, it offers in addition a side-effecting `update` method | `xs union ys` |Multiset union; same as `xs ++ ys`.| | `xs.distinct` |A subsequence of `xs` that contains no duplicated element.| -Trait [Seq](http://www.scala-lang.org/api/current/scala/collection/Seq.html) has two subtraits [LinearSeq](http://www.scala-lang.org/api/current/scala/collection/LinearSeq.html), and [IndexedSeq](http://www.scala-lang.org/api/current/scala/collection/IndexedSeq.html). These do not add any new operations, but each offers different performance characteristics: A linear sequence has efficient `head` and `tail` operations, whereas an indexed sequence has efficient `apply`, `length`, and (if mutable) `update` operations. Frequently used linear sequences are `scala.collection.immutable.List` and `scala.collection.immutable.Stream`. Frequently used indexed sequences are `scala.Array` and `scala.collection.mutable.ArrayBuffer`. The `Vector` class provides an interesting compromise between indexed and linear access. It has both effectively constant time indexing overhead and constant time linear access overhead. Because of this, vectors are a good foundation for mixed access patterns where both indexed and linear accesses are used. You'll learn more on vectors [later](concrete-immutable-collection-classes.html#vectors). +Trait [Seq](http://www.scala-lang.org/api/current/scala/collection/Seq.html) has two subtraits [LinearSeq](http://www.scala-lang.org/api/current/scala/collection/LinearSeq.html), and [IndexedSeq](http://www.scala-lang.org/api/current/scala/collection/IndexedSeq.html). These do not add any new operations, but each offers different performance characteristics: A linear sequence has efficient `head` and `tail` operations, whereas an indexed sequence has efficient `apply`, `length`, and (if mutable) `update` operations. Frequently used linear sequences are `scala.collection.immutable.List` and `scala.collection.immutable.Stream`. Frequently used indexed sequences are `scala.Array` and `scala.collection.mutable.ArrayBuffer`. The `Vector` class provides an interesting compromise between indexed and linear access. It has both effectively constant time indexing overhead and constant time linear access overhead. Because of this, vectors are a good foundation for mixed access patterns where both indexed and linear accesses are used. You'll learn more on vectors [later](concrete-immutable-collection-classes.html). ### Buffers ### diff --git a/_overviews/collections/sets.md b/_overviews/collections/sets.md index 027d3b4af3..4b06a0501f 100644 --- a/_overviews/collections/sets.md +++ b/_overviews/collections/sets.md @@ -107,7 +107,7 @@ Comparing the two interactions shows an important principle. You often can repla Mutable sets also provide add and remove as variants of `+=` and `-=`. The difference is that `add` and `remove` return a Boolean result indicating whether the operation had an effect on the set. -The current default implementation of a mutable set uses a hashtable to store the set's elements. The default implementation of an immutable set uses a representation that adapts to the number of elements of the set. An empty set is represented by just a singleton object. Sets of sizes up to four are represented by a single object that stores all elements as fields. Beyond that size, immutable sets are implemented as [hash tries](concrete-immutable-collection-classes.html#hash-tries). +The current default implementation of a mutable set uses a hashtable to store the set's elements. The default implementation of an immutable set uses a representation that adapts to the number of elements of the set. An empty set is represented by just a singleton object. Sets of sizes up to four are represented by a single object that stores all elements as fields. Beyond that size, immutable sets are implemented as [hash tries](concrete-immutable-collection-classes.html). A consequence of these representation choices is that, for sets of small sizes (say up to 4), immutable sets are usually more compact and also more efficient than mutable sets. So, if you expect the size of a set to be small, try making it immutable. diff --git a/_overviews/core/actors-migration-guide.md b/_overviews/core/actors-migration-guide.md index 4d2604f9bf..834ccef22f 100644 --- a/_overviews/core/actors-migration-guide.md +++ b/_overviews/core/actors-migration-guide.md @@ -75,8 +75,6 @@ The AMK resides both in the Scala actors and in the *akka-actor.jar*. Future maj To start the migration user needs to add the *scala-actors.jar* and the *scala-actors-migration.jar* to the build of their projects. Addition of *scala-actors.jar* and *scala-actors-migration.jar* enables the usage of the AMK described below. - These artifacts reside in the [Scala Tools](https://oss.sonatype.org/content/groups/scala-tools/org/scala-lang/) - repository and in the [Scala distribution](http://www.scala-lang.org/downloads). ### Step by Step Migration Actor Migration Kit should be used in 5 steps. Each step is designed to introduce minimal changes diff --git a/_overviews/macros/blackbox-whitebox.md b/_overviews/macros/blackbox-whitebox.md index 4fc2519bb9..aade9367f2 100644 --- a/_overviews/macros/blackbox-whitebox.md +++ b/_overviews/macros/blackbox-whitebox.md @@ -35,7 +35,7 @@ compehensibility. However sometimes def macros transcend the notion of "just a regular method". For example, it is possible for a macro expansion to yield an expression of a type that is more specific than the return type of a macro. In Scala 2.10, such expansion will retain its precise type as highlighted in the ["Static return type of Scala macros"](http://stackoverflow.com/questions/13669974/static-return-type-of-scala-macros) article at Stack Overflow. -This curious feature provides additional flexibility, enabling [fake type providers](http://meta.plasm.us/posts/2013/07/11/fake-type-providers-part-2/), [extended vanilla materialization](/sips/pending/source-locations.html), [fundep materialization]({{ site.baseurl }}/overviews/macros/implicits.html#fundep-materialization) and [extractor macros](https://github.com/scala/scala/commit/84a335916556cb0fe939d1c51f27d80d9cf980dc), but it also sacrifices clarity - both for humans and for machines. +This curious feature provides additional flexibility, enabling [fake type providers](http://meta.plasm.us/posts/2013/07/11/fake-type-providers-part-2/), [extended vanilla materialization](/sips/source-locations.html), [fundep materialization]({{ site.baseurl }}/overviews/macros/implicits.html#fundep-materialization) and [extractor macros](https://github.com/scala/scala/commit/84a335916556cb0fe939d1c51f27d80d9cf980dc), but it also sacrifices clarity - both for humans and for machines. To concretize the crucial distinction between macros that behave just like normal methods and macros that refine their return types, we introduce the notions of blackbox macros and whitebox macros. Macros that faithfully follow their type signatures are called **blackbox macros** as their implementations are irrelevant to understanding their behaviour (could be treated as black boxes). Macros that can't have precise signatures in Scala's type system are called **whitebox macros** (whitebox def macros do have signatures, but these signatures are only approximations). @@ -51,7 +51,7 @@ Blackbox def macros are treated differently from def macros of Scala 2.10. The f 1. When an application of a blackbox macro expands into tree `x`, the expansion is wrapped into a type ascription `(x: T)`, where `T` is the declared return type of the blackbox macro with type arguments and path dependencies applied in consistency with the particular macro application being expanded. This invalidates blackbox macros as an implementation vehicle of [type providers](http://meta.plasm.us/posts/2013/07/11/fake-type-providers-part-2/). 1. When an application of a blackbox macro still has undetermined type parameters after Scala's type inference algorithm has finished working, these type parameters are inferred forcedly, in exactly the same manner as type inference happens for normal methods. This makes it impossible for blackbox macros to influence type inference, prohibiting [fundep materialization]({{ site.baseurl }}/overviews/macros/implicits.html#fundep-materialization). -1. When an application of a blackbox macro is used as an implicit candidate, no expansion is performed until the macro is selected as the result of the implicit search. This makes it impossible to [dynamically calculate availability of implicit macros]({{ site.baseurl }}/sips/rejected/source-locations.html). -1. When an application of a blackbox macro is used as an extractor in a pattern match, it triggers an unconditional compiler error, preventing [customizations of pattern matching](https://github.com/paulp/scala/commit/84a335916556cb0fe939d1c51f27d80d9cf980dc) implemented with macros. +1. When an application of a blackbox macro is used as an implicit candidate, no expansion is performed until the macro is selected as the result of the implicit search. This makes it impossible to [dynamically calculate availability of implicit macros]({{ site.baseurl }}/sips/source-locations.html). +1. When an application of a blackbox macro is used as an extractor in a pattern match, it triggers an unconditional compiler error, preventing customizations of pattern matching implemented with macros. Whitebox def macros work exactly like def macros used to work in Scala 2.10. No restrictions of any kind get applied, so everything that could be done with macros in 2.10 should be possible in 2.11 and 2.12. diff --git a/_overviews/macros/changelog211.md b/_overviews/macros/changelog211.md index 45c9f154f4..0b91acfb4c 100644 --- a/_overviews/macros/changelog211.md +++ b/_overviews/macros/changelog211.md @@ -9,7 +9,6 @@ overview-name: Macros num: 13 -languages: [ja] permalink: /overviews/macros/:title.html --- @@ -27,7 +26,7 @@ Quasiquotes is the single most impressive upgrade for reflection and macros in S 1) **[Fundep materialization](implicits.html#fundep-materialization)**. Since Scala 2.10.2, implicit whitebox macros can be used to materialize instances of type classes, however such materialized instances can't guide type inference. In Scala 2.11.0, materializers can also affect type inference, helping scalac to infer type arguments for enclosing method applications, something that's used with great success in Shapeless. Even more, with the fix of [SI-3346](https://issues.scala-lang.org/browse/SI-3346), this inference guiding capability can affect both normal methods and implicit conversions alike. Please note, however, that fundep materialization doesn't let one change how Scala's type inference works, but merely provides a way to throw more type constraints into the mix, so it's, for example, impossible to make type inference flow from right to left using fundep materializers. -2) **[Extractor macros](https://github.com/paulp/scala/commit/84a335916556cb0fe939d1c51f27d80d9cf980dc)**. A prominent new feature in Scala 2.11.0 is [name-based extractors](https://github.com/scala/scala/pull/2848) implemented by Paul Phillips. And as usual, when there's a Scala feature, it's very likely that macros can make use of it. Indeed, with the help of structural types, whitebox macros can be used to write extractors than refine the types of extractees on case-by-case basis. This is the technique that we use internally to implement quasiquotes. +2) **Extractor macros**. A prominent new feature in Scala 2.11.0 is [name-based extractors](https://github.com/scala/scala/pull/2848) implemented by Paul Phillips. And as usual, when there's a Scala feature, it's very likely that macros can make use of it. Indeed, with the help of structural types, whitebox macros can be used to write extractors than refine the types of extractees on case-by-case basis. This is the technique that we use internally to implement quasiquotes. 3) **[Named and default arguments in macros](https://github.com/scala/scala/pull/3543)**. This is something that strictly speaking shouldn't belong to this changelog, because this feature was reverted shortly after being merged into Scala 2.11.0-RC1 due to a tiny mistake that led to a regression, but we've got a patch that makes the macro engine understand named/default arguments in macro applications. Even though the code freeze won't let us bring this change in Scala 2.11.0, we expect to merge it in Scala 2.11.1 at an earliest opportunity. diff --git a/_overviews/macros/typemacros.md b/_overviews/macros/typemacros.md index 15ed40ae44..b43172f8e5 100644 --- a/_overviews/macros/typemacros.md +++ b/_overviews/macros/typemacros.md @@ -30,7 +30,7 @@ Just as def macros make the compiler execute custom functions when it sees invoc Db.Coffees.update(brazilian.copy(price = 10)) println(Db.Coffees.all) -The full source code of the `H2Db` type macro is provided [at GitHub](https://github.com/xeno-by/typemacros-h2db), and this guide covers its most important aspects. First the macro generates the statically typed database wrapper by connecting to a database at compile-time (tree generation is explained in [the reflection overview]({{ site.baseurl }}/overviews/reflection/overview.html)). Then it uses the NEW `c.introduceTopLevel` API ([Scaladoc](https://scala-webapps.epfl.ch/jenkins/view/misc/job/macro-paradise211-nightly-main/ws/dists/latest/doc/scala-devel-docs/api/index.html#scala.reflect.macros.Synthetics)) to insert the generated wrapper into the list of top-level definitions maintained by the compiler. Finally, the macro returns an `Apply` node, which represents a super constructor call to the generated class. NOTE that type macros are supposed to expand into `c.Tree`, unlike def macros, which expand into `c.Expr[T]`. That's because `Expr`s represent terms, while type macros expand into types. +The full source code of the `H2Db` type macro is provided [at GitHub](https://github.com/xeno-by/typemacros-h2db), and this guide covers its most important aspects. First the macro generates the statically typed database wrapper by connecting to a database at compile-time (tree generation is explained in [the reflection overview]({{ site.baseurl }}/overviews/reflection/overview.html)). Then it uses the NEW `c.introduceTopLevel` API to insert the generated wrapper into the list of top-level definitions maintained by the compiler. Finally, the macro returns an `Apply` node, which represents a super constructor call to the generated class. NOTE that type macros are supposed to expand into `c.Tree`, unlike def macros, which expand into `c.Expr[T]`. That's because `Expr`s represent terms, while type macros expand into types. type H2Db(url: String) = macro impl @@ -75,7 +75,7 @@ Type macros represent a hybrid between def macros and type members. On the one h | Can be inherited | Yes | Yes | Yes | | Can override and be overridden | Yes | Yes | Yes | -In Scala programs type macros can appear in one of five possible roles: type role, applied type role, parent type role, new role and annotation role. Depending on the role in which a macro is used, which can be inspected with the NEW `c.macroRole` API ([Scaladoc](https://scala-webapps.epfl.ch/jenkins/view/misc/job/macro-paradise-nightly-main/ws/dists/latest/doc/scala-devel-docs/api/index.html#scala.reflect.macros.Enclosures)), its list of allowed expansions is different. +In Scala programs type macros can appear in one of five possible roles: type role, applied type role, parent type role, new role and annotation role. Depending on the role in which a macro is used, which can be inspected with the NEW `c.macroRole` API, its list of allowed expansions is different. | Role | Example | Class | Non-class? | Apply? | Template? | |--------------|-------------------------------------------------|-------|------------|--------|-----------| diff --git a/_overviews/macros/untypedmacros.md b/_overviews/macros/untypedmacros.md index d03a4f3109..309f67ce3a 100644 --- a/_overviews/macros/untypedmacros.md +++ b/_overviews/macros/untypedmacros.md @@ -74,4 +74,4 @@ nothing changes for them (and you won't be able to specify any return type for a Finally the untyped macros patch enables using `c.Tree` instead of `c.Expr[T]` everywhere in signatures of macro implementations. Both for parameters and return types, all four combinations of untyped/typed in macro def and tree/expr in macro impl are supported. -Check our unit tests for more information: [test/files/run/macro-untyped-conformance](https://github.com/scalamacros/kepler/blob/b55bda4860a205c88e9ae27015cf2d6563cc241d/test/files/run/macro-untyped-conformance/Impls_Macros_1.scala). +Check our unit tests for more information: test/files/run/macro-untyped-conformance. diff --git a/_overviews/parallel-collections/ctries.md b/_overviews/parallel-collections/ctries.md index c5c8e9e079..ccd9fbcdb7 100644 --- a/_overviews/parallel-collections/ctries.md +++ b/_overviews/parallel-collections/ctries.md @@ -9,7 +9,7 @@ overview-name: Parallel Collections num: 4 -languages: [ja, zh-cn, es, ru] +languages: [ja, zh-cn, ru] permalink: /overviews/parallel-collections/:title.html --- diff --git a/_overviews/parallel-collections/overview.md b/_overviews/parallel-collections/overview.md index c3b69b97ad..f397d957cc 100644 --- a/_overviews/parallel-collections/overview.md +++ b/_overviews/parallel-collections/overview.md @@ -99,7 +99,7 @@ Using a parallel `map` to transform a collection of `String` to all-uppercase: Summing via `fold` on a `ParArray`: - scala> val parArray = (1 to 10000).toArray.par + scala> val parArray = (1 to 10000).toArray.par parArray: scala.collection.parallel.mutable.ParArray[Int] = ParArray(1, 2, 3, ... scala> parArray.fold(0)(_ + _) @@ -192,13 +192,13 @@ declared outside of the closure which is passed to `foreach`. sum: Int = 0 scala> list.foreach(sum += _); sum - res02: Int = 457073 + res02: Int = 457073 scala> var sum = 0 sum: Int = 0 scala> list.foreach(sum += _); sum - res03: Int = 468520 + res03: Int = 468520 Here, we can see that each time `sum` is reinitialized to 0, and `foreach` is called again on `list`, `sum` holds a different value. The source of this @@ -273,5 +273,4 @@ broken into partitions A, B, C, in that order, will be reassembled once again in the order A, B, C. Not some other arbitrary order like B, C, A. For more on how parallel collections split and combine operations on different -parallel collection types, see the [Architecture]({{ site.baseurl }}/overviews -/parallel-collections/architecture.html) section of this guide. +parallel collection types, see the [Architecture]({{ site.baseurl }}/overviews/parallel-collections/architecture.html) section of this guide. diff --git a/_overviews/reflection/changelog211.md b/_overviews/reflection/changelog211.md index 92c7f2e173..83a03d0858 100644 --- a/_overviews/reflection/changelog211.md +++ b/_overviews/reflection/changelog211.md @@ -7,7 +7,6 @@ overview-name: Reflection num: 7 -languages: [ja] permalink: /overviews/reflection/:title.html --- diff --git a/_overviews/reflection/symbols-trees-types.md b/_overviews/reflection/symbols-trees-types.md index 5a8de3151d..5702e04eb3 100644 --- a/_overviews/reflection/symbols-trees-types.md +++ b/_overviews/reflection/symbols-trees-types.md @@ -45,8 +45,8 @@ entity, such as a top-level package, then its owner is the special `NoSymbol` singleton object. Representing a missing symbol, `NoSymbol` is commonly used in the API to denote an empty or default value. Accessing the `owner` of `NoSymbol` throws an exception. See the API docs for the general -interface provided by type -[`Symbol`](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/reflect/api/Symbols$SymbolApi.html) +interface provided by type `Symbol` + ### `TypeSymbol`s @@ -140,7 +140,7 @@ example: res0: scala.reflect.runtime.universe.Type = scala.List[Int] In this example, a -[`scala.reflect.api.Types$TypeRef`](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/reflect/api/Types$TypeRef.html) +`scala.reflect.api.Types$TypeRef` is returned, which corresponds to the type constructor `List`, applied to the type argument `Int`. diff --git a/_overviews/tutorials/scala-with-maven.md b/_overviews/tutorials/scala-with-maven.md index b0641484fd..d8f8194ec5 100644 --- a/_overviews/tutorials/scala-with-maven.md +++ b/_overviews/tutorials/scala-with-maven.md @@ -298,6 +298,6 @@ I'm not going to explain all of Maven in this tutorial (though I hope to add mor [31]: http://mvnrepository.com [32]: http://docs.scala-lang.org/contribute.html [33]: http://maven.apache.org/plugins/maven-eclipse-plugin/ -[34]: http://mojo.codehaus.org/build-helper-maven-plugin/ +[34]: http://www.mojohaus.org/build-helper-maven-plugin/ [35]: https://github.com/sonatype/m2eclipse-scala [36]: https://github.com/scala/scala-module-dependency-sample diff --git a/_pl/tour/abstract-types.md b/_pl/tour/abstract-types.md index 4d152a4940..5e8a9a4e36 100644 --- a/_pl/tour/abstract-types.md +++ b/_pl/tour/abstract-types.md @@ -76,4 +76,4 @@ object AbstractTypeTest2 extends App { } ``` -Należy też pamiętać o zastosowaniu [adnotacji wariancji](variance.html). Inaczej nie byłoby możliwe ukrycie konkretnego typu sekwencji obiektu zwracanego przez metodę `newIntSeqBuf`. +Należy też pamiętać o zastosowaniu [adnotacji wariancji](variances.html). Inaczej nie byłoby możliwe ukrycie konkretnego typu sekwencji obiektu zwracanego przez metodę `newIntSeqBuf`. diff --git a/_pl/tour/anonymous-function-syntax.md b/_pl/tour/anonymous-function-syntax.md deleted file mode 100644 index 60a428f3b8..0000000000 --- a/_pl/tour/anonymous-function-syntax.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -layout: tour -title: Funkcje anonimowe - -discourse: false - -partof: scala-tour - -num: 6 -language: pl -next-page: higher-order-functions -previous-page: mixin-class-composition ---- - -Scala posiada lekką składnię pozwalającą na definiowanie funkcji anonimowych. Poniższe wyrażenie tworzy funkcję następnika dla liczb całkowitych: - -```tut -(x: Int) => x + 1 -``` - -Jest to krótsza forma deklaracji anonimowej klasy: - -```tut -new Function1[Int, Int] { - def apply(x: Int): Int = x + 1 -} -``` - -Możliwe jest także zdefiniowanie funkcji z wieloma parametrami: - -```tut -(x: Int, y: Int) => "(" + x + ", " + y + ")" -``` - -lub też bez parametrów: - -```tut -() => { System.getProperty("user.dir") } -``` - -Istnieje także prosty sposób definicji typów funkcji. Dla powyższych funkcji można je określić w następujący sposób: - -``` -Int => Int -(Int, Int) => String -() => String -``` - -Jest to skrócona forma dla poniższych typów: - -``` -Function1[Int, Int] -Function2[Int, Int, String] -Function0[String] -``` diff --git a/_pl/tour/basics.md b/_pl/tour/basics.md new file mode 100644 index 0000000000..9ca6062b48 --- /dev/null +++ b/_pl/tour/basics.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: Basics + +discourse: false + +partof: scala-tour +language: pl +--- diff --git a/_pl/tour/by-name-parameters.md b/_pl/tour/by-name-parameters.md new file mode 100644 index 0000000000..d0bdd220a3 --- /dev/null +++ b/_pl/tour/by-name-parameters.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: By-name Parameters + +discourse: false + +partof: scala-tour +language: pl +--- diff --git a/_pl/tour/compound-types.md b/_pl/tour/compound-types.md index 84ebd0d963..278efe5be4 100644 --- a/_pl/tour/compound-types.md +++ b/_pl/tour/compound-types.md @@ -8,7 +8,7 @@ partof: scala-tour num: 23 language: pl -next-page: explicitly-typed-self-references +next-page: self-types previous-page: abstract-types --- diff --git a/_pl/tour/default-parameter-values.md b/_pl/tour/default-parameter-values.md index 5b32053260..f1eddf538f 100644 --- a/_pl/tour/default-parameter-values.md +++ b/_pl/tour/default-parameter-values.md @@ -8,7 +8,7 @@ partof: scala-tour num: 32 language: pl -next-page: named-parameters +next-page: named-arguments previous-page: annotations --- @@ -70,4 +70,4 @@ val m3 = new HashMap[String,Int](20,0.8f) val m4 = new HashMap[String,Int](loadFactor = 0.8f) ``` -Należy zwrócić uwagę, w jaki sposób możemy wykorzystać *dowolną* domyślną wartość poprzez użycie [parametrów nazwanych](named-parameters.html). +Należy zwrócić uwagę, w jaki sposób możemy wykorzystać *dowolną* domyślną wartość poprzez użycie [parametrów nazwanych](named-arguments.html). diff --git a/_pl/tour/extractor-objects.md b/_pl/tour/extractor-objects.md index 5b3e20f5e6..306b96d478 100644 --- a/_pl/tour/extractor-objects.md +++ b/_pl/tour/extractor-objects.md @@ -8,7 +8,7 @@ partof: scala-tour num: 15 language: pl -next-page: sequence-comprehensions +next-page: generic-classes previous-page: regular-expression-patterns --- @@ -40,4 +40,4 @@ Typ zwracany przez `unapply` powinien odpowiadać jednemu przypadkowi: Zdarza się, że chcielibyśmy dopasować określoną liczbę wartości oraz sekwencję. Z tego powodu możesz także zdefiniować wzorce poprzez metodę `unapplySeq`. Ostatnia wartość typu `Tn` powinna być `Seq[S]`. Ten mechanizm pozwala na dopasowanie wzorców takich jak `case List(x1, ..., xn)`. -Ekstraktory sprawiają, że kod jest łatwiejszy do utrzymania. Aby dowiedzieć się więcej, możesz przeczytać publikację ["Matching Objects with Patterns"](http://lamp.epfl.ch/~emir/written/MatchingObjectsWithPatterns-TR.pdf) (zobacz sekcję 4) autorstwa Emir, Odersky i Williams (styczeń 2007). +Ekstraktory sprawiają, że kod jest łatwiejszy do utrzymania. Aby dowiedzieć się więcej, możesz przeczytać publikację ["Matching Objects with Patterns"](https://infoscience.epfl.ch/record/98468/files/MatchingObjectsWithPatterns-TR.pdf) (zobacz sekcję 4) autorstwa Emir, Odersky i Williams (styczeń 2007). diff --git a/_pl/tour/for-comprehensions.md b/_pl/tour/for-comprehensions.md new file mode 100644 index 0000000000..4c64e85d08 --- /dev/null +++ b/_pl/tour/for-comprehensions.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: For Comprehensions + +discourse: false + +partof: scala-tour +language: pl +--- diff --git a/_pl/tour/generic-classes.md b/_pl/tour/generic-classes.md index c822d2087d..c570e76ecc 100644 --- a/_pl/tour/generic-classes.md +++ b/_pl/tour/generic-classes.md @@ -9,7 +9,7 @@ partof: scala-tour num: 17 language: pl next-page: variances -previous-page: sequence-comprehensions +previous-page: extractor-objects --- Scala posiada wbudowaną obsługą klas parametryzowanych przez typy. Tego typu klasy generyczne są szczególnie użyteczne podczas tworzenia klas kolekcji. diff --git a/_pl/tour/higher-order-functions.md b/_pl/tour/higher-order-functions.md index c93ea72c71..8d9ee188bb 100644 --- a/_pl/tour/higher-order-functions.md +++ b/_pl/tour/higher-order-functions.md @@ -9,7 +9,7 @@ partof: scala-tour num: 7 language: pl next-page: nested-functions -previous-page: anonymous-function-syntax +previous-page: mixin-class-composition --- Scala pozwala na definiowanie funkcji wyższego rzędu. Są to funkcje, które przyjmują funkcje jako parametry lub których wynik jest też funkcją. Poniżej znajduje się przykład funkcji `apply`, która pobiera inną funkcję `f` i wartość `v` po to, by zwrócić wynik zastosowania `f` do `v`: @@ -21,7 +21,7 @@ def apply(f: Int => String, v: Int) = f(v) _Uwaga: metody są automatycznie zamieniane na funkcje, jeżeli wymaga tego kontekst_ Praktyczny przykład: - + ```tut class Decorator(left: String, right: String) { def layout[A](x: A) = left + x.toString() + right @@ -33,7 +33,7 @@ object FunTest extends App { println(apply(decorator.layout, 7)) } ``` - + Wykonanie zwraca poniższy wynik: ``` diff --git a/_pl/tour/implicit-parameters.md b/_pl/tour/implicit-parameters.md index 4bac40487a..2f84032a5d 100644 --- a/_pl/tour/implicit-parameters.md +++ b/_pl/tour/implicit-parameters.md @@ -9,7 +9,7 @@ partof: scala-tour num: 25 language: pl next-page: implicit-conversions -previous-page: explicitly-typed-self-references +previous-page: self-types --- Metodę z _parametrami domniemanymi_ można stosować tak samo jak każdą zwyczajną metodę. W takim przypadku etykieta `implicit` nie ma żadnego znaczenia. Jednak jeżeli odpowiednie argumenty dla parametrów domniemanych nie zostaną jawnie określone, to kompilator dostarczy je automatycznie. diff --git a/_pl/tour/mixin-class-composition.md b/_pl/tour/mixin-class-composition.md index 58765aeab0..5a2ec415ea 100644 --- a/_pl/tour/mixin-class-composition.md +++ b/_pl/tour/mixin-class-composition.md @@ -8,7 +8,7 @@ partof: scala-tour num: 5 language: pl -next-page: anonymous-function-syntax +next-page: higher-order-functions previous-page: traits --- @@ -23,7 +23,7 @@ abstract class AbsIterator { def next(): T } ``` - + Następnie rozważmy klasę domieszkową, która doda do klasy `AbsIterator` metodę `foreach` wykonującą podaną funkcję dla każdego elementu zwracanego przez iterator. Aby zdefiniować klasę domieszkową, użyjemy słowa kluczowego `trait`: ```tut @@ -31,9 +31,9 @@ trait RichIterator extends AbsIterator { def foreach(f: T => Unit) { while (hasNext) f(next()) } } ``` - + Oto przykład konkretnego iteratora, który zwraca kolejne znaki w podanym łańcuchu znaków: - + ```tut class StringIterator(s: String) extends AbsIterator { type T = Char @@ -42,9 +42,9 @@ class StringIterator(s: String) extends AbsIterator { def next() = { val ch = s charAt i; i += 1; ch } } ``` - + Chcielibyśmy także połączyć funkcjonalność `StringIterator` oraz `RichIterator` w jednej klasie. Z pojedynczym dziedziczeniem czy też samymi interfejsami jest to niemożliwe, gdyż obie klasy zawierają implementacje metod. Scala pozwala na rozwiązanie tego problemu z użyciem _kompozycji domieszek_. Umożliwia ona ponowne wykorzystanie różnicy definicji klas, tzn. wszystkich definicji, które nie zostały odziedziczone. Ten mechanizm pozwala nam na połączenie `StringIterator` z `RichIterator`, tak jak w poniższym przykładzie - gdzie chcielibyśmy wypisać w kolumnie wszystkie znaki z danego łańcucha: - + ```tut object StringIteratorTest { def main(args: Array[String]) { @@ -54,5 +54,5 @@ object StringIteratorTest { } } ``` - + Klasa `iter` w funkcji `main` jest skonstruowana wykorzystując kompozycję domieszek `StringIterator` oraz `RichIterator` z użyciem słowa kluczowego `with`. Pierwszy rodzic jest nazywany _klasą bazową_ `Iter`, podczas gdy drugi (i każdy kolejny) rodzic jest nazywany _domieszką_. diff --git a/_pl/tour/named-parameters.md b/_pl/tour/named-arguments.md similarity index 100% rename from _pl/tour/named-parameters.md rename to _pl/tour/named-arguments.md diff --git a/_pl/tour/explicitly-typed-self-references.md b/_pl/tour/self-types.md similarity index 100% rename from _pl/tour/explicitly-typed-self-references.md rename to _pl/tour/self-types.md diff --git a/_pl/tour/sequence-comprehensions.md b/_pl/tour/sequence-comprehensions.md deleted file mode 100644 index c477ee25e0..0000000000 --- a/_pl/tour/sequence-comprehensions.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -layout: tour -title: Instrukcje for (For comprehension) - -discourse: false - -partof: scala-tour - -num: 16 -language: pl -next-page: generic-classes -previous-page: extractor-objects ---- - -Scala posiada lekką składnię do wyrażania instrukcji for. Tego typu wyrażania przybierają formę `for (enumerators) yield e`, gdzie `enumerators` oznacza listę enumeratorów oddzielonych średnikami. *Enumerator* może być generatorem wprowadzającym nowe zmienne albo filtrem. Wyrażenie `e` określa wynik dla każdego powiązania wygenerowanego przez enumeratory i zwraca sekwencję tych wartości. - -Przykład: - -```tut -object ComprehensionTest1 extends App { - def even(from: Int, to: Int): List[Int] = - for (i <- List.range(from, to) if i % 2 == 0) yield i - Console.println(even(0, 20)) -} -``` - -To wyrażenie for w funkcji `even` wprowadza nową zmienną `i` typu `Int`, która jest kolejno wiązana ze wszystkimi wartościami listy `List(from, from + 1, ..., to - 1)`. Instrukcja `if i % 2 == 0` filtruje wszystkie liczby nieparzyste, tak aby ciało tego wyrażenia było obliczane tylko dla liczb parzystych. Ostatecznie całe to wyrażenie zwraca listę liczb parzystych. - -Program zwraca następujący wynik: - -``` -List(0, 2, 4, 6, 8, 10, 12, 14, 16, 18) -``` - -Poniżej bardziej skomplikowany przykład, który oblicza wszystkie pary liczb od `0` do `n-1`, których suma jest równa danej wartości `v`: - -```tut -object ComprehensionTest2 extends App { - def foo(n: Int, v: Int) = - for (i <- 0 until n; - j <- i until n if i + j == v) yield - (i, j); - foo(20, 32) foreach { - case (i, j) => - println(s"($i, $j)") - } -} -``` - -Ten przykład pokazuje, że wyrażenia for nie są ograniczone do list. Każdy typ danych, który wspiera operacje: `withFilter`, `map` oraz `flatMap` (z odpowiednimi typami), może być użyty w instrukcjach for. - -Wynik powyższego programu: - -``` -(13, 19) -(14, 18) -(15, 17) -(16, 16) -``` - -Istnieje szczególna postać instrukcji for, które zwracają `Unit`. Tutaj wiązania utworzone przez listę generatorów i filtrów są użyte do wykonania efektów ubocznych. Aby to osiągnąć, należy pominąć słowo kluczowe `yield`: - -``` -object ComprehensionTest3 extends App { - for (i <- Iterator.range(0, 20); - j <- Iterator.range(i, 20) if i + j == 32) - println(s"($i, $j)") -} -``` diff --git a/_pl/tour/singleton-objects.md b/_pl/tour/singleton-objects.md index 653c10ac88..3c50539a37 100644 --- a/_pl/tour/singleton-objects.md +++ b/_pl/tour/singleton-objects.md @@ -25,9 +25,9 @@ object Blah { Metoda `sum` jest dostępna globalnie i można się do niej odwołać lub importować jako `test.Blah.sum`. -Obiekty singleton są swego rodzaju skrótem do definiowania pojedynczej instancji klasy, która nie powinna być bezpośrednio tworzona i która sama w sobie stanowi referencję do tego obiektu, jakby była określona jako `val`. +Obiekty singleton są swego rodzaju skrótem do definiowania pojedynczej instancji klasy, która nie powinna być bezpośrednio tworzona i która sama w sobie stanowi referencję do tego obiektu, jakby była określona jako `val`. -Obiekt singleton może rozszerzać klasę lub cechę. Przykładowo [klasa przypadku](case-class.html) bez [parametrów typu](generic-class.html) domyślnie generuje obiekt singleton o tej samej nazwie, który implementuje cechę [`Function*`](http://www.scala-lang.org/api/current/scala/Function1.html). +Obiekt singleton może rozszerzać klasę lub cechę. Przykładowo [klasa przypadku](case-classes.html) bez [parametrów typu](generic-classes.html) domyślnie generuje obiekt singleton o tej samej nazwie, który implementuje cechę [`Function*`](http://www.scala-lang.org/api/current/scala/Function1.html). ## Obiekt towarzyszący ## diff --git a/_pl/tour/tour-of-scala.md b/_pl/tour/tour-of-scala.md index 936a18277f..0f3f1d255f 100644 --- a/_pl/tour/tour-of-scala.md +++ b/_pl/tour/tour-of-scala.md @@ -18,9 +18,9 @@ Scala jest nowoczesnym, wieloparadygmatowym językiem programowania zaprojektowa Scala jest czysto obiektowym językiem w tym sensie, że każda [wartość jest obiektem](unified-types.html). Typy oraz zachowania obiektów są opisane przez [klasy](classes.html) oraz [cechy](traits.html). Klasy są rozszerzane przez podtypowanie i elastyczny mechanizm [kompozycji domieszek](mixin-class-composition.html) jako zastępnik dla wielodziedziczenia. ## Scala jest funkcyjna ## -Scala jest też funkcyjnym językiem w tym sensie, że [każda funkcja jest wartością](unified-types.html). Scala dostarcza [lekką składnię](anonymous-function-syntax.html) do definiowana funkcji anonimowych, wspiera [funkcje wyższego rzędu](higher-order-functions.html), pozwala funkcjom, by były [zagnieżdżone](nested-functions.html), a także umożliwia [rozwijanie funkcji](currying.html). [Klasy przypadków](case-classes.html) oraz wbudowane wsparcie dla [dopasowania wzorców](pattern-matching.html) wprowadzają do Scali mechanizm typów algebraicznych stosowany w wielu funkcyjnych językach programowania. [Obiekty singleton](singleton-objects) są wygodną metodą grupowania funkcji, które nie należą do żadnej klasy. +Scala jest też funkcyjnym językiem w tym sensie, że [każda funkcja jest wartością](unified-types.html). Scala dostarcza lekką składnię do definiowana funkcji anonimowych, wspiera [funkcje wyższego rzędu](higher-order-functions.html), pozwala funkcjom, by były [zagnieżdżone](nested-functions.html), a także umożliwia [rozwijanie funkcji](currying.html). [Klasy przypadków](case-classes.html) oraz wbudowane wsparcie dla [dopasowania wzorców](pattern-matching.html) wprowadzają do Scali mechanizm typów algebraicznych stosowany w wielu funkcyjnych językach programowania. [Obiekty singleton](singleton-objects.html) są wygodną metodą grupowania funkcji, które nie należą do żadnej klasy. -Ponadto mechanizm dopasowania wzorca w naturalny sposób rozszerza się do obsługi [przetwarzania danych w formacie XML](xml-processing.html) z pomocą [wzorców sekwencji ignorujących prawą stronę](regular-expression-patterns.html), z wykorzystaniem rozszerzeń [obiektów ekstraktorów](extractor-objects.html). W tym kontekście [instrukcje for](sequence-comprehensions.html) są użyteczne w formułowaniu zapytań. Ta funkcjonalność sprawia, że Scala jest idealnym językiem do tworzenia aplikacji takich jak usługi sieciowe. +Ponadto mechanizm dopasowania wzorca w naturalny sposób rozszerza się do obsługi przetwarzania danych w formacie XML z pomocą [wzorców sekwencji ignorujących prawą stronę](regular-expression-patterns.html), z wykorzystaniem rozszerzeń [obiektów ekstraktorów](extractor-objects.html). W tym kontekście instrukcje for są użyteczne w formułowaniu zapytań. Ta funkcjonalność sprawia, że Scala jest idealnym językiem do tworzenia aplikacji takich jak usługi sieciowe. ## Scala jest statycznie typowana ## Scala posiada ekspresywny system typów zapewniający, że abstrakcje są używane w sposób zgodny oraz bezpieczny. W szczególności system typów wspiera: @@ -30,7 +30,7 @@ Scala posiada ekspresywny system typów zapewniający, że abstrakcje są używa * [górne](upper-type-bounds.html) oraz [dolne](lower-type-bounds.html) ograniczenia typów * [klasy zagnieżdżone](inner-classes.html) i [typy abstrakcyjne](abstract-types.html) jako elementy obiektów * [typy złożone](compound-types.html) -* [jawnie typowane samoreferencje](explicitly-typed-self-references.html) +* [jawnie typowane samoreferencje](self-types.html) * [parametry domniemane](implicit-parameters.html) i [konwersje niejawne](implicit-conversions.html) * [metody polimorficzne](polymorphic-methods.html) @@ -44,4 +44,4 @@ W praktyce rozwiązania specyficzne dla domeny wymagają odpowiednich rozszerze Powyższe mechanizmy pozwalają na definicję nowych rodzajów wyrażeń bez potrzeby rozszerzania składni języka czy też wykorzystywania meta-programowania w postaci makr. -Scala jest zaprojektowana tak, aby współpracować dobrze ze środowiskiem uruchomieniowym JRE oraz językiem Java. Funkcje Javy takie jak [adnotacje](annotations.html) oraz typy generyczne posiadają swoje bezpośrednie odwzorowanie w Scali. Unikalne funkcje Scali, jak na przykład [domyślne wartości parametrów](default-parameter-values.html) oraz [nazwane parametry](named-parameters.html), są kompilowane tak, aby zachować jak największą zgodność z Javą. Scala ma także taki sam model kompilacji (oddzielna kompilacja, dynamiczne ładowanie klas), dzięki czemu umożliwia korzystanie z całego ekosystemu Javy. +Scala jest zaprojektowana tak, aby współpracować dobrze ze środowiskiem uruchomieniowym JRE oraz językiem Java. Funkcje Javy takie jak [adnotacje](annotations.html) oraz typy generyczne posiadają swoje bezpośrednie odwzorowanie w Scali. Unikalne funkcje Scali, jak na przykład [domyślne wartości parametrów](default-parameter-values.html) oraz [nazwane parametry](named-arguments.html), są kompilowane tak, aby zachować jak największą zgodność z Javą. Scala ma także taki sam model kompilacji (oddzielna kompilacja, dynamiczne ładowanie klas), dzięki czemu umożliwia korzystanie z całego ekosystemu Javy. diff --git a/_pt-br/tour/annotations.md b/_pt-br/tour/annotations.md index 56032eaecb..3b262897de 100644 --- a/_pt-br/tour/annotations.md +++ b/_pt-br/tour/annotations.md @@ -35,7 +35,7 @@ O significado das cláusulas de anotação é _dependente da implementação_. N No exemplo a seguir, adicionamos a anotação `throws` à definição do método `read` para capturar a exceção lançada no código Java. -> Um compilador Java verifica se um programa contém manipuladores para [exceções verificadas](http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html) analisando quais exceções verificadas podem resultar da execução de um método ou construtor. Para cada exceção verificada que é um resultado possível, a cláusula **throws** para o método ou construtor _deve_ mencionar a classe dessa exceção ou uma das superclasses da classe dessa exceção. +> Um compilador Java verifica se um programa contém manipuladores para exceções verificadas analisando quais exceções verificadas podem resultar da execução de um método ou construtor. Para cada exceção verificada que é um resultado possível, a cláusula **throws** para o método ou construtor _deve_ mencionar a classe dessa exceção ou uma das superclasses da classe dessa exceção. > Como Scala não tem exceções verificadas, os métodos Scala _devem_ ser anotados com uma ou mais anotações `throws`, de forma que o código Java possa capturar exceções lançadas por um método Scala. diff --git a/_pt-br/tour/anonymous-function-syntax.md b/_pt-br/tour/anonymous-function-syntax.md deleted file mode 100644 index 94120e366b..0000000000 --- a/_pt-br/tour/anonymous-function-syntax.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -layout: tour -title: Sintaxe de Função Anônima - -discourse: false - -partof: scala-tour - -num: 6 -next-page: higher-order-functions -previous-page: mixin-class-composition -language: pt-br ---- - -Scala fornece uma sintaxe relativamente leve para definir funções anônimas. A expressão a seguir cria uma função sucessor para inteiros: - -```tut -(x: Int) => x + 1 -``` - -Isso é uma abreviação para a definição de classe anônima a seguir: - -```tut -new Function1[Int, Int] { - def apply(x: Int): Int = x + 1 -} -``` - -Também é possível definir funções com múltiplos parâmetros: - -```tut -(x: Int, y: Int) => "(" + x + ", " + y + ")" -``` - -ou sem parâmetros: - -```tut -() => { System.getProperty("user.dir") } -``` - -Há também uma forma muito simples de escrever tipos de funções. Aqui estão os tipos da três funções acima definidas: - -``` -Int => Int -(Int, Int) => String -() => String -``` - -Essa sintaxe é uma abreviação para os seguintes tipos: - -``` -Function1[Int, Int] -Function2[Int, Int, String] -Function0[String] -``` diff --git a/_pt-br/tour/basics.md b/_pt-br/tour/basics.md new file mode 100644 index 0000000000..b61c4a110d --- /dev/null +++ b/_pt-br/tour/basics.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: Basics + +discourse: false + +partof: scala-tour +language: pt-br +--- diff --git a/_pt-br/tour/by-name-parameters.md b/_pt-br/tour/by-name-parameters.md new file mode 100644 index 0000000000..f470f57d05 --- /dev/null +++ b/_pt-br/tour/by-name-parameters.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: By-name Parameters + +discourse: false + +partof: scala-tour +language: pt-br +--- diff --git a/_pt-br/tour/classes.md b/_pt-br/tour/classes.md index 1b9f46df7a..a3718ca93e 100644 --- a/_pt-br/tour/classes.md +++ b/_pt-br/tour/classes.md @@ -45,7 +45,7 @@ object Classes { } ``` -O programa define uma aplicação executável chamada Classes como um [Objeto Singleton](singleton-objects) dentro do método `main`. O método `main` cria um novo `Ponto` e armazena o valor em `pt`. Perceba que valores definidos com o construtor `val` são diferentes das variáveis definidas com o construtor `var` (veja acima a classe `Ponto`), `val` não permite atualização do valor, ou seja, o valor é uma constante. +O programa define uma aplicação executável chamada Classes como um [Objeto Singleton](singleton-objects.html) dentro do método `main`. O método `main` cria um novo `Ponto` e armazena o valor em `pt`. Perceba que valores definidos com o construtor `val` são diferentes das variáveis definidas com o construtor `var` (veja acima a classe `Ponto`), `val` não permite atualização do valor, ou seja, o valor é uma constante. Aqui está a saída do programa: diff --git a/_pt-br/tour/compound-types.md b/_pt-br/tour/compound-types.md index 0b06a4b1ba..2639ddff3d 100644 --- a/_pt-br/tour/compound-types.md +++ b/_pt-br/tour/compound-types.md @@ -7,7 +7,7 @@ discourse: false partof: scala-tour num: 23 -next-page: explicitly-typed-self-references +next-page: self-types previous-page: abstract-types language: pt-br --- diff --git a/_pt-br/tour/default-parameter-values.md b/_pt-br/tour/default-parameter-values.md index dedcc4e702..2553bc5cad 100644 --- a/_pt-br/tour/default-parameter-values.md +++ b/_pt-br/tour/default-parameter-values.md @@ -7,7 +7,7 @@ discourse: false partof: scala-tour num: 32 -next-page: named-parameters +next-page: named-arguments previous-page: annotations language: pt-br --- @@ -39,7 +39,7 @@ public class HashMap { public static final float DEFAULT_LOAD_FACTOR = 0.75; public HashMap(Map m); - /** Cria um novo HashMap com capacidade padrão (16) + /** Cria um novo HashMap com capacidade padrão (16) * e fator de carga padrão (0.75) */ public HashMap(); @@ -71,5 +71,5 @@ val m3 = new HashMap[String,Int](20,0.8f) val m4 = new HashMap[String,Int](loadFactor = 0.8f) ``` -Observe como podemos tirar proveito de *qualquer* valor padrão usando [parâmetros nomeados](named-parameters.html). +Observe como podemos tirar proveito de *qualquer* valor padrão usando [parâmetros nomeados](named-arguments.html). diff --git a/_pt-br/tour/extractor-objects.md b/_pt-br/tour/extractor-objects.md index d1e71d4330..4508c778a3 100644 --- a/_pt-br/tour/extractor-objects.md +++ b/_pt-br/tour/extractor-objects.md @@ -7,7 +7,7 @@ discourse: false partof: scala-tour num: 15 -next-page: sequence-comprehensions +next-page: generic-classes previous-page: regular-expression-patterns language: pt-br --- diff --git a/_pt-br/tour/for-comprehensions.md b/_pt-br/tour/for-comprehensions.md new file mode 100644 index 0000000000..a1363d1cc1 --- /dev/null +++ b/_pt-br/tour/for-comprehensions.md @@ -0,0 +1,9 @@ +--- +layout: tour +title: For Comprehensions + +discourse: false + +partof: scala-tour +language: pt-br +--- diff --git a/_pt-br/tour/generic-classes.md b/_pt-br/tour/generic-classes.md index b9e8fe31bc..f892ed9514 100644 --- a/_pt-br/tour/generic-classes.md +++ b/_pt-br/tour/generic-classes.md @@ -8,7 +8,7 @@ partof: scala-tour num: 17 next-page: variances -previous-page: sequence-comprehensions +previous-page: extractor-objects language: pt-br --- @@ -45,4 +45,4 @@ A saída do programa é: 97 1 ``` -_Nota: subtipos de tipos genéricos são *invariantes*. Isto significa que se tivermos uma pilha de caracteres do tipo `Stack[Char]` então ela não pode ser usada como uma pilha de inteiros do tipo `Stack[Int]`. Isso seria incorreto porque isso nos permitiria inserir inteiros verdadeiros na pilha de caracteres. Para concluir, `Stack[T]` é um subtipo de de `Stack[S]` se e somente se `S = T`. Como isso pode ser bastante restritivo, Scala oferece um [mecanismo de anotação de parâmetro de tipo](variances.html) para controlar o comportamento de subtipo de tipos genéricos._ \ No newline at end of file +_Nota: subtipos de tipos genéricos são *invariantes*. Isto significa que se tivermos uma pilha de caracteres do tipo `Stack[Char]` então ela não pode ser usada como uma pilha de inteiros do tipo `Stack[Int]`. Isso seria incorreto porque isso nos permitiria inserir inteiros verdadeiros na pilha de caracteres. Para concluir, `Stack[T]` é um subtipo de de `Stack[S]` se e somente se `S = T`. Como isso pode ser bastante restritivo, Scala oferece um [mecanismo de anotação de parâmetro de tipo](variances.html) para controlar o comportamento de subtipo de tipos genéricos._ diff --git a/_pt-br/tour/higher-order-functions.md b/_pt-br/tour/higher-order-functions.md index 8cb5f3acc6..7cb79017bf 100644 --- a/_pt-br/tour/higher-order-functions.md +++ b/_pt-br/tour/higher-order-functions.md @@ -8,7 +8,7 @@ partof: scala-tour num: 7 next-page: nested-functions -previous-page: anonymous-function-syntax +previous-page: mixin-class-composition language: pt-br --- @@ -21,7 +21,7 @@ def apply(f: Int => String, v: Int) = f(v) _Nota: métodos são automaticamente convertidos em funções se o contexto demandar.**_ Outro exemplo: - + ```tut class Decorator(left: String, right: String) { def layout[A](x: A) = left + x.toString() + right @@ -33,7 +33,7 @@ object FunTest extends App { println(apply(decorator.layout, 7)) } ``` - + A execução produz a saída: ``` diff --git a/_pt-br/tour/implicit-parameters.md b/_pt-br/tour/implicit-parameters.md index 60177c17cb..e960414647 100644 --- a/_pt-br/tour/implicit-parameters.md +++ b/_pt-br/tour/implicit-parameters.md @@ -8,7 +8,7 @@ partof: scala-tour num: 25 next-page: implicit-conversions -previous-page: explicitly-typed-self-references +previous-page: self-types language: pt-br --- diff --git a/_pt-br/tour/mixin-class-composition.md b/_pt-br/tour/mixin-class-composition.md index 96d62bdbee..4d000b3896 100644 --- a/_pt-br/tour/mixin-class-composition.md +++ b/_pt-br/tour/mixin-class-composition.md @@ -7,14 +7,14 @@ discourse: false partof: scala-tour num: 5 -next-page: anonymous-function-syntax +next-page: higher-order-functions previous-page: traits language: pt-br --- _Nota de tradução: A palavra `mixin` pode ser traduzida como mescla, porém é preferível utilizar a notação original_ Ao contrário de linguagens que suportam somente _herança simples_, Scala tem uma noção mais abrangente sobre a reutilização de classes. Scala torna possível reutilizar a _nova definição de membros de uma classe_ (por exemplo: o relacionamento delta para com a superclasse) na definição de uma nova classe. Isso é expressado como uma _composição de classe mixin ou mixin-class composition_. Considere a seguinte abstração para iterators. - + ```tut abstract class AbsIterator { type T @@ -22,17 +22,17 @@ abstract class AbsIterator { def next(): T } ``` - + A seguir, considere a classe mixin que estende `AbsIterator` com um método `foreach` que aplica uma dada função para cada elemento retornado pelo iterator. Para definir tal classe que será utilizada como um mixin a palavra-chave `trait` deve ser declarada. - + ```tut trait RichIterator extends AbsIterator { def foreach(f: T => Unit) { while (hasNext) f(next()) } } ``` - + Aqui uma classes iterator concreta a qual retorna sucessivos caracteres de uma dada string: - + ```tut class StringIterator(s: String) extends AbsIterator { type T = Char @@ -41,9 +41,9 @@ class StringIterator(s: String) extends AbsIterator { def next() = { val ch = s charAt i; i += 1; ch } } ``` - + Poderíamos combinar a funcionalidade de `StringIterator` e `RichIterator` em uma só classe. Com herança simples e interfaces isso é impossível, pois ambas as classes contém implementações para seus membros. Scala nos ajuda com a sua _composição de classes mixin_. Isso permite que programadores reutilizem o delta de uma definição de uma classe, por exemplo: todas as novas definições não são herdadas. Esse mecanismo torna possível combinar `StringIterator` com `RichIterator`, como pode ser visto no programa teste a seguir, que imprime uma coluna de todos os caracteres de uma dada string. - + ```tut object StringIteratorTest { def main(args: Array[String]) { @@ -53,5 +53,5 @@ object StringIteratorTest { } } ``` - + A classe `Iter` na função `main` é construída a partir de uma composição dos pais `StringIterator` e `RichIterator` com a palavra-chave `with`. O primeiro pai é chamado de _superclass_ de `Iter`, já o segundo pai (e qualquer outro que venha após) é chamado de _mixin_ ou mescla. diff --git a/_pt-br/tour/named-parameters.md b/_pt-br/tour/named-arguments.md similarity index 100% rename from _pt-br/tour/named-parameters.md rename to _pt-br/tour/named-arguments.md diff --git a/_pt-br/tour/explicitly-typed-self-references.md b/_pt-br/tour/self-types.md similarity index 100% rename from _pt-br/tour/explicitly-typed-self-references.md rename to _pt-br/tour/self-types.md diff --git a/_pt-br/tour/sequence-comprehensions.md b/_pt-br/tour/sequence-comprehensions.md deleted file mode 100644 index 6bd993b926..0000000000 --- a/_pt-br/tour/sequence-comprehensions.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -layout: tour -title: Sequence Comprehensions - -discourse: false - -partof: scala-tour - -num: 16 -next-page: generic-classes -previous-page: extractor-objects -language: pt-br ---- - -Scala oferece uma notação simples para expressar *compreensões de sequência*. As compreensões têm a forma `for (enumerators) yield e`, onde` enumerators` se refere a uma lista de enumeradores separados por ponto-e-vírgula. Um *enumerator* é um gerador que introduz novas variáveis ou é um filtro. A compreensão avalia o corpo `e` para cada associação gerada pelos enumeradores e retorna uma sequência desses valores. - -Por exemplo: - -```tut -object ComprehensionTest1 extends App { - def par(de: Int, ate: Int): List[Int] = - for (i <- List.range(de, ate) if i % 2 == 0) yield i - Console.println(par(0, 20)) -} -``` - -A função for-expression introduz uma nova variável `i` do tipo `Int`, que é subsequentemente associada a todos os valores da lista `List (de, de + 1, ..., ate - 1)`. A restrição `if i% 2 == 0` ignora todos os números ímpares para que o corpo (que só consiste na expressão i) seja avaliado somente para números pares. Consequentemente, toda a expressão `for` retorna uma lista de números pares. - -O programa produz a seguinte saída: - -``` -List(0, 2, 4, 6, 8, 10, 12, 14, 16, 18) -``` - -Agora um exemplo mais complicado que calcula todos os pares de números entre `0` e` n-1` cuja soma é igual a um dado valor `v`: - -```tut -object ComprehensionTest2 extends App { - def foo(n: Int, v: Int) = - for (i <- 0 until n; - j <- i until n if i + j == v) yield - (i, j); - foo(20, 32) foreach { - case (i, j) => - println(s"($i, $j)") - } -} -``` - -Este exemplo mostra que as compreensões não estão restritas às listas. Pois o programa anterior usa iteradores. Todo tipo de dados que suporta as operações `withFilter`, `map`, e `flatMap` (com os tipos apropriados) pode ser usado em compreensões de sequência. - -Aqui está a saída do programa: - -``` -(13, 19) -(14, 18) -(15, 17) -(16, 16) -``` - -Há também uma forma especial de compreensão de sequência que retorna `Unit`. Aqui as associações que são criadas a partir da lista de geradores e filtros são utilizadas para gerar efeitos colaterais. O programador precisa omitir a palavra-chave `yield` para fazer uso de tal compreensão de sequência. -Aqui está um programa que é equivalente ao anterior, mas usa uma forma especial de for-expression que retorna `Unit`: - -``` -object ComprehensionTest3 extends App { - for (i <- Iterator.range(0, 20); - j <- Iterator.range(i, 20) if i + j == 32) - println(s"($i, $j)") -} -``` diff --git a/_pt-br/tour/tour-of-scala.md b/_pt-br/tour/tour-of-scala.md index 8e0bdb9d14..01f75ac1a9 100644 --- a/_pt-br/tour/tour-of-scala.md +++ b/_pt-br/tour/tour-of-scala.md @@ -18,9 +18,9 @@ Scala é uma linguagem de programação moderna e multi-paradigma desenvolvida p Scala é uma linguagem puramente orientada a objetos no sentido que [todo valor é um objeto](unified-types.html). Tipos e comportamentos de objetos são descritos por [classes](classes.html) e [traits](traits.html). Classes são estendidas por subclasses e por um flexível mecanismo [de composição mesclada](mixin-class-composition.html) como uma alternativa para herança múltipla. ## Scala é funcional ## -Scala é também uma linguagem funcional no sentido que [toda função é um valor](unified-types.html). Scala fornece uma [sintaxe leve](anonymous-function-syntax.html) para definir funções anônimas, suporta [funções de primeira ordem](higher-order-functions.html), permite funções [aninhadas](nested-functions.html), e suporta [currying](currying.html). As [case classes](case-classes.html) da linguagem Scala e o suporte embutido para [correspondência de padrões](pattern-matching.html) modelam tipos algébricos utilizados em muitas linguagens de programação funcional. [Objetos Singleton](singleton-objects.html) fornecem uma alternativa conveniente para agrupar funções que não são membros de uma classe. +Scala é também uma linguagem funcional no sentido que [toda função é um valor](unified-types.html). Scala fornece uma sintaxe leve para definir funções anônimas, suporta [funções de primeira ordem](higher-order-functions.html), permite funções [aninhadas](nested-functions.html), e suporta [currying](currying.html). As [case classes](case-classes.html) da linguagem Scala e o suporte embutido para [correspondência de padrões](pattern-matching.html) modelam tipos algébricos utilizados em muitas linguagens de programação funcional. [Objetos Singleton](singleton-objects.html) fornecem uma alternativa conveniente para agrupar funções que não são membros de uma classe. -Além disso, a noção de correspondência de padrões em Scala se estende naturalmente ao [processamento de dados de um XML](xml-processing.html) com a ajuda de [expressões regulares](regular-expression-patterns.html), por meio de uma extensão via [objetos extratores](extractor-objects.html). Nesse contexto, [compreensões de sequência](sequence-comprehensions.html) são úteis para formular consultas. Essas funcionalidades tornam Scala ideal para desenvolver aplicações como serviços web. +Além disso, a noção de correspondência de padrões em Scala se estende naturalmente ao processamento de dados de um XML com a ajuda de [expressões regulares](regular-expression-patterns.html), por meio de uma extensão via [objetos extratores](extractor-objects.html). Nesse contexto, compreensões de sequência são úteis para formular consultas. Essas funcionalidades tornam Scala ideal para desenvolver aplicações como serviços web. ## Scala é estaticamente tipada ## Scala é equipada com um expressivo sistema de tipos que reforça estaticamente que abstrações são utilizadas de uma forma segura e coerente. Particularmente, o sistema de tipos suporta: @@ -30,7 +30,7 @@ Scala é equipada com um expressivo sistema de tipos que reforça estaticamente * [Limites de tipos superiores](upper-type-bounds.html) e [limites de tipos inferiores](lower-type-bounds.html), * [Classes internas](inner-classes.html) e [tipos abstratos](abstract-types.html) como membros de um objeto * [Tipos compostos](compound-types.html) -* [Auto referências explicitamente tipadas](explicitly-typed-self-references.html) +* [Auto referências explicitamente tipadas](self-types.html) * [parâmetros implícitos](implicit-parameters.html) e [conversões implícitas](implicit-conversions.html) * [métodos polimórficos](polymorphic-methods.html) @@ -45,6 +45,6 @@ Na prática, o desenvolvimento de aplicações de um determinado domínio geralm Uma utilização conjunta de ambos os recursos facilita a definição de novas instruções sem estender a sintaxe e sem usar meta-programação como macros. -Scala é projetada para interoperar bem com o popular Java 2 Runtime Environment (JRE). Em particular, a interação com a linguagem de programação orientada a objetos Java é o mais suave possível. Funcionalidades novas do Java como [annotations](annotations.html) e Java generics têm correspondentes diretos em Scala. Esses recursos Scala sem correspondentes Java, como [valor default de parâmetros](default-parameter-values.html) e [parâmetros nomeados](named-parameters.html), compilam de forma semelhante ao Java. Scala tem o mesmo modelo de compilação que Java (compilação separada, carregamento de classe dinâmica) e permite o acesso a milhares de bibliotecas de alta qualidade existentes. +Scala é projetada para interoperar bem com o popular Java 2 Runtime Environment (JRE). Em particular, a interação com a linguagem de programação orientada a objetos Java é o mais suave possível. Funcionalidades novas do Java como [annotations](annotations.html) e Java generics têm correspondentes diretos em Scala. Esses recursos Scala sem correspondentes Java, como [valor default de parâmetros](default-parameter-values.html) e [parâmetros nomeados](named-arguments.html), compilam de forma semelhante ao Java. Scala tem o mesmo modelo de compilação que Java (compilação separada, carregamento de classe dinâmica) e permite o acesso a milhares de bibliotecas de alta qualidade existentes. Continue na próxima página para ler mais. diff --git a/_ru/overviews/parallel-collections/concrete-parallel-collections.md b/_ru/overviews/parallel-collections/concrete-parallel-collections.md index 81c7807c89..f0985016b8 100644 --- a/_ru/overviews/parallel-collections/concrete-parallel-collections.md +++ b/_ru/overviews/parallel-collections/concrete-parallel-collections.md @@ -24,7 +24,7 @@ num: 2 scala> pa map (x => (x - 1) / 2) res1: scala.collection.parallel.mutable.ParArray[Int] = ParArray(0, 1, 2, 3, 4, 5, 6, 7,... -Реализация разбивки параллельного массива [разделителями]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html#core_abstractions) сводится к созданию двух новых разделителей с последующим обновлением их итерационных индексов. [Компоновщики]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html#core_abstractions) играют более заметную роль. Так как мы не знаем заранее количество элементов (и следовательно, размер массива) при выполнении большинства методов трансформации (например, `flatMap`, `filter`, `takeWhile`, и т.д.), каждый компоновщик, в сущности, является массивом-буфером, у которого операция `+=` требует для выполнения амортизированное постоянное время. Разные процессоры добавляют элементы к отдельным компоновщикам параллельного массива, которые потом по цепочке объединяют свои внутренние массивы. Лежащий в основе массив размещается и параллельно заполняется только после того, как становится известным общее число элементов. По этой причине методы трансформации требуют больше ресурсов, чем методы получения доступа. Также стоит заметить, что финальное размещение массива выполняется JVM последовательно, поэтому этот момент может стать узким местом, если даже сама операция отображения весьма нересурсоемкая. +Реализация разбивки параллельного массива [разделителями]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html) сводится к созданию двух новых разделителей с последующим обновлением их итерационных индексов. [Компоновщики]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html) играют более заметную роль. Так как мы не знаем заранее количество элементов (и следовательно, размер массива) при выполнении большинства методов трансформации (например, `flatMap`, `filter`, `takeWhile`, и т.д.), каждый компоновщик, в сущности, является массивом-буфером, у которого операция `+=` требует для выполнения амортизированное постоянное время. Разные процессоры добавляют элементы к отдельным компоновщикам параллельного массива, которые потом по цепочке объединяют свои внутренние массивы. Лежащий в основе массив размещается и параллельно заполняется только после того, как становится известным общее число элементов. По этой причине методы трансформации требуют больше ресурсов, чем методы получения доступа. Также стоит заметить, что финальное размещение массива выполняется JVM последовательно, поэтому этот момент может стать узким местом, если даже сама операция отображения весьма нересурсоемкая. Вызов метода `seq` приводит к преобразованию параллельного массива в коллекцию `ArraySeq`, которая является его последовательным аналогом. Такое преобразование эффективно, и в основе `ArraySeq` остается тот же массив, что и был у исходного параллельного. @@ -38,8 +38,8 @@ num: 2 scala> pv filter (_ % 2 == 0) res0: scala.collection.parallel.immutable.ParVector[Int] = ParVector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18,... -Неизменяемые векторы представлены 32-ичными деревьями (32-way trees), поэтому [разделители]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html#core_abstractions) разбивают их, назначая по поддереву каждому новому разделителю. -[Компоновщики]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html#core_abstractions) в настоящий момент хранят вектор из элементов и компонуют путем отложенного копирования. По этой причине методы трансформации менее масштабируемы по сравнению с теми же методами параллельного массива. Как только в будущем релизе Scala станет доступной операция конкатенации векторов, компоновщики станут образовываться путем конкатенации, и от этого методы трансформации станут гораздо более эффективными. +Неизменяемые векторы представлены 32-ичными деревьями (32-way trees), поэтому [разделители]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html) разбивают их, назначая по поддереву каждому новому разделителю. +[Компоновщики]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html) в настоящий момент хранят вектор из элементов и компонуют путем отложенного копирования. По этой причине методы трансформации менее масштабируемы по сравнению с теми же методами параллельного массива. Как только в будущем релизе Scala станет доступной операция конкатенации векторов, компоновщики станут образовываться путем конкатенации, и от этого методы трансформации станут гораздо более эффективными. Параллельный вектор является параллельным аналогом последовательной коллекции [Vector](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/immutable/Vector.html), и преобразования одного в другое занимают постоянное время. @@ -53,7 +53,7 @@ num: 2 scala> 15 to 5 by -2 par res1: scala.collection.parallel.immutable.ParRange = ParRange(15, 13, 11, 9, 7, 5) -Подобно тому, как последовательные диапазоны не имеют строителей, параллельные диапазоны не имеют [компоновщиков]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html#core_abstractions). При создании отображения (mapping) элементов параллельного диапазона получается параллельный вектор. Последовательные и параллельные диапазоны могут эффективно преобразовываться друг в друга вызовами методов `seq` и `par`. +Подобно тому, как последовательные диапазоны не имеют строителей, параллельные диапазоны не имеют [компоновщиков]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html). При создании отображения (mapping) элементов параллельного диапазона получается параллельный вектор. Последовательные и параллельные диапазоны могут эффективно преобразовываться друг в друга вызовами методов `seq` и `par`. ## Параллельные хэш-таблицы @@ -79,7 +79,7 @@ num: 2 scala> phs map { x => x * x } sum res0: Int = 332833500 -[Компоновщики]({{ site.baseurl }}/overviews/parallel-collections/architecture.html#core_abstractions) параллельных хэш-деревьев действуют аналогично компоновщикам хэш-таблиц, а именно предварительно распределяют элементы по блокам, а после этого параллельно составляют результирующее хэш-дерево, назначая обработку различных блоков разным процессорам, каждый из которых независимо собирает свое поддерево. +[Компоновщики]({{ site.baseurl }}/overviews/parallel-collections/architecture.html) параллельных хэш-деревьев действуют аналогично компоновщикам хэш-таблиц, а именно предварительно распределяют элементы по блокам, а после этого параллельно составляют результирующее хэш-дерево, назначая обработку различных блоков разным процессорам, каждый из которых независимо собирает свое поддерево. Параллельные хэш-деревья могут за постоянное время преобразовываться вызовами методов `seq` и `par` в последовательные хэш-деревья и обратно. @@ -106,7 +106,7 @@ num: 2 (4.0,2.0000000929222947) ... -[Компоновщики]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html#core_abstractions) реализованы как `TrieMap`-- так как эта структура является многопоточной, при вызове метода трансформации создается только один компоновщик, разделяемый всеми процессорами. +[Компоновщики]({{ site.baseurl }}/ru/overviews/parallel-collections/architecture.html) реализованы как `TrieMap`-- так как эта структура является многопоточной, при вызове метода трансформации создается только один компоновщик, разделяемый всеми процессорами. Как и в случае с другими параллельными изменяемыми коллекциями, экземпляры `TrieMap` и параллельных `ParTrieMap`, полученные вызовом методов `seq` или `par`, хранят данные в одном и том же хранилище, поэтому модификации одной коллекции видны в другой. Такие преобразования занимают постоянное время. diff --git a/_ru/overviews/parallel-collections/overview.md b/_ru/overviews/parallel-collections/overview.md index 5d2f43f083..2d68d91d8d 100644 --- a/_ru/overviews/parallel-collections/overview.md +++ b/_ru/overviews/parallel-collections/overview.md @@ -50,7 +50,7 @@ language: ru Попробуем изобразить всеобщность и полезность представленных коллекций на ряде простых примеров, для каждого из которых характерно прозрачно-параллельное выполнение. -_Примечание:_ Некоторые из последующих примеров оперируют небольшими коллекциями, для которых такой подход не рекомендуется. Они должны рассматриваться только как иллюстрация. Эвристически, ускорение становится заметным, когда размер коллекции дорастает до нескольких тысяч элементов. (Более подробно о взаимосвязи между размером коллекции и производительностью, смотрите [соответствующий подраздел]({{ site.baseurl}}/overviews/parallel-collections/performance.html#how_big_should_a_collection_be_to_go_parallel) раздела, посвященного [производительности]({{ site.baseurl }}/ru/overviews/parallel-collections/performance.html) в данном руководстве.) +_Примечание:_ Некоторые из последующих примеров оперируют небольшими коллекциями, для которых такой подход не рекомендуется. Они должны рассматриваться только как иллюстрация. Эвристически, ускорение становится заметным, когда размер коллекции дорастает до нескольких тысяч элементов. (Более подробно о взаимосвязи между размером коллекции и производительностью, смотрите [соответствующий подраздел]({{ site.baseurl}}/overviews/parallel-collections/performance.html) раздела, посвященного [производительности]({{ site.baseurl }}/ru/overviews/parallel-collections/performance.html) в данном руководстве.) #### map @@ -66,7 +66,7 @@ _Примечание:_ Некоторые из последующих прим Суммируем через `fold` на `ParArray`: - scala> val parArray = (1 to 10000).toArray.par + scala> val parArray = (1 to 10000).toArray.par parArray: scala.collection.parallel.mutable.ParArray[Int] = ParArray(1, 2, 3, ... scala> parArray.fold(0)(_ + _) @@ -131,13 +131,13 @@ _На заметку:_ Коллекции, являющиеся последов sum: Int = 0 scala> list.foreach(sum += _); sum - res02: Int = 457073 + res02: Int = 457073 scala> var sum = 0 sum: Int = 0 scala> list.foreach(sum += _); sum - res03: Int = 468520 + res03: Int = 468520 В примере видно, что несмотря на то, что каждый раз `sum` инициализируется в 0, при каждом новом вызове `foreach` на предложенном `list`, `sum` получает различное значение. Источником недетерминизма является так называемая _гонка_-- параллельное чтение/запись одной и той же изменяемой переменной. diff --git a/_sips/minutes/2016-07-15-sip-minutes.md b/_sips/minutes/2016-07-15-sip-minutes.md index e7a93ca02e..d72ed724cc 100644 --- a/_sips/minutes/2016-07-15-sip-minutes.md +++ b/_sips/minutes/2016-07-15-sip-minutes.md @@ -24,7 +24,7 @@ Quick iteration through all the SLIPs: * [Extensions of Futures and Promises ](https://github.com/scala/slip/issues/7) * [Implicit enrichment of Either to support Monadic bias](https://github.com/scala/slip/pull/20) * [Adding scala.io.Target](https://github.com/scala/slip/pull/2) -* [SLIP 27 - Redesigning collection views](https://github.com/scala/slip/blob/master/text/0027-collection-view-redesign.md) +* SLIP 27 - Redesigning collection views Jorge Vicente Cantero was the Process Lead and acting secretary of the meeting. diff --git a/_sips/minutes/2016-08-16-sip-10th-august-minutes.md b/_sips/minutes/2016-08-16-sip-10th-august-minutes.md index d7a5c45b3d..c10feb9347 100644 --- a/_sips/minutes/2016-08-16-sip-10th-august-minutes.md +++ b/_sips/minutes/2016-08-16-sip-10th-august-minutes.md @@ -12,7 +12,7 @@ The following agenda was distributed to attendees: | Topic | Reviewer | | --- | --- | | [SIP-12: Uncluttering Scala's syntax for control structures](http://docs.scala-lang.org/sips/pending/uncluttering-control.html) | Seth Tisue | -| [SIP-16: Self-cleaning macros](http://docs.scala-lang.org/sips/pending/self-cleaning-macros.html) | Eugene Burmako | +| [SIP-16: Self-cleaning macros](http://docs.scala-lang.org/sips/self-cleaning-macros.html) | Eugene Burmako | | [SIP-21: Spores](http://docs.scala-lang.org/sips/pending/spores.html) | Martin Odersky | | [SIP-23: Literal-based singleton types](http://docs.scala-lang.org/sips/pending/42.type.html) | Adriaan Moors | | [SIP-24: Repeated by-name parameters](http://docs.scala-lang.org/sips/pending/repeated-byname.html) | Andrew Marki | diff --git a/_sips/minutes/2017-05-08-sip-minutes.md b/_sips/minutes/2017-05-08-sip-minutes.md index 9aa74aff02..e5d2e52ccf 100644 --- a/_sips/minutes/2017-05-08-sip-minutes.md +++ b/_sips/minutes/2017-05-08-sip-minutes.md @@ -13,7 +13,7 @@ The following agenda was distributed to attendees: | --- | --- | --- | | [SIP-NN - comonadic-comprehensions](http://docs.scala-lang.org/sips/comonadic-comprehensions.html) | Shimi Bandiel | Rejected | | [SIP-33 - Match infix & prefix types to meet expression rules](http://docs.scala-lang.org/sips/make-types-behave-like-expressions.html)| Oron Port | Pending | -|[Scala Library Changes](scala/scala-dev#323)|Adriaan Moors| Scala-dev proposal | +|[Scala Library Changes](https://github.com/scala/scala-dev/issues/323)|Adriaan Moors| Scala-dev proposal | Jorge Vicente Cantero was the Process Lead. @@ -84,7 +84,7 @@ Skipped since they are waiting for the prototype from the author of the proposal **Adriaan** agrees with that. He believes that is probably too painful to change anything about it. - **Jorge** proposes to keep thinking on this and to discuss it in the next two months, migration cycle. + **Jorge** proposes to keep thinking on this and to discuss it in the next two months, migration cycle. **Seth** said that as the 2.13 cycle progresses will bring more information and feedback about the usage. He believes that it is a good start to begin with and they’ll know more as they go through it. diff --git a/_sips/sip-submission.md b/_sips/sip-submission.md index a9018cd24d..66f160062b 100644 --- a/_sips/sip-submission.md +++ b/_sips/sip-submission.md @@ -323,7 +323,7 @@ The process to submit is simple: * Create a new SIP file in the `sips/pending/_posts/`. Use the [S(L)IP template](https://github.com/scala/docs.scala-lang/blob/master/_sips/sip-template.md) * Make sure the new file follows the format: `YYYY-MM-dd-{title}.md`. Use the proposal date for `YYYY-MM-dd`. * Use the [Markdown Syntax](http://daringfireball.net/projects/markdown/syntax) to write your SIP. - * Follow the instructions in the [README](https://github.com/scala/docs.scala-lang/blob/gh-pages/README.md) to build your SIP locally so you can ensure that it looks correct on the website. + * Follow the instructions in the [README](https://github.com/scala/docs.scala-lang/) to build your SIP locally so you can ensure that it looks correct on the website. * Create a link to your SIP in the "pending sips" section of `index.md` * Commit your changes to your forked repository * Create a new [pull request](https://github.com/scala/docs.scala-lang/pull/new/gh-pages). This will notify the Scala SIP team. diff --git a/_sips/sip-tutorial.md b/_sips/sip-tutorial.md index d620c1d4c7..680eee2d73 100644 --- a/_sips/sip-tutorial.md +++ b/_sips/sip-tutorial.md @@ -10,7 +10,7 @@ This tutorial details of how to write a new SIP and adding it to the website. The process to submit is simple: * Fork the [Scala documentation repository](http://github.com/scala/docs.scala-lang) and clone it. -* Create a new SIP file in the `sips/pending/_posts/`. Use the [S(L)IP template](https://github.com/scala/slip/blob/master/slip-template.md) +* Create a new SIP file in the `sips/pending/_posts/`. Use the [S(L)IP template](https://github.com/scala/docs.scala-lang/blob/master/_sips/sip-template.md) * Make sure the new file follows the format: `YYYY-MM-dd-{title}.md`. Use the proposal date for `YYYY-MM-dd`. * Use the [Markdown Syntax](http://daringfireball.net/projects/markdown/syntax) to write your SIP. * Follow the instructions in the [README](https://github.com/scala/docs.scala-lang/blob/master/README.md) to build your SIP locally so you can ensure that it looks correct on the website. @@ -34,7 +34,7 @@ Use the [Markdown Syntax](http://daringfireball.net/projects/markdown/syntax) to If you would like a starting point, clone the [SIP Template](./sip-template.html) in `sips/pending/sip-template.md` and use that. -See the [source](https://github.com/scala/docs.scala-lang/blob/gh-pages/sips/sip-tutorial.md) for this document (`sip-tutorial.md`) for how to do syntax highlighting. +See the [source](https://github.com/scala/docs.scala-lang/blob/master/_sips/sip-template.md) for this document (`sip-tutorial.md`) for how to do syntax highlighting. {% highlight scala %} class Foo diff --git a/_sips/sips/2010-01-22-scala-2-8-arrays.md b/_sips/sips/2010-01-22-scala-2-8-arrays.md index ba5b9d72da..0d25473b08 100644 --- a/_sips/sips/2010-01-22-scala-2-8-arrays.md +++ b/_sips/sips/2010-01-22-scala-2-8-arrays.md @@ -278,8 +278,7 @@ three language features will be described in more detail in separate notes. ## References 1. [David MacIver. Scala arrays. Blog, June 2008.][1] 2. [Matt Malone. The mystery of the parameterized array. Blog, August 2009.][2] -3. [David MacIver. Refactoring scala.array. Pre-SIP (Scala Improvement Proposal), October 2008.][3] +3. David MacIver. Refactoring scala.array. Pre-SIP (Scala Improvement Proposal), October 2008. - [1]: http://www.drmaciver.com/2008/06/scala- arrays + [1]: http://www.drmaciver.com/2008/06/scala-arrays [2]: http://oldfashionedsoftware.com/2009/08/05/the-mystery-of-the-parameterized-array - [3]: http://www.drmaciver.com/repos/scala-arrays/sip-arrays.xhtml diff --git a/_sips/sips/2011-10-13-uncluttering-control.md b/_sips/sips/2011-10-13-uncluttering-control.md index 8170c53c70..d855b1287d 100644 --- a/_sips/sips/2011-10-13-uncluttering-control.md +++ b/_sips/sips/2011-10-13-uncluttering-control.md @@ -4,7 +4,7 @@ title: SIP-12 - Uncluttering Scala’s syntax for control structures. redirect_from: "/sips/pending/uncluttering-control.html" vote-status: rejected -vote-text: The committee votes unanimously to reject the change. The conclusion is that there is not a clear benefit for it and the required invested time and efforts would be too high. For more explanation, read the minutes. +vote-text: The committee votes unanimously to reject the change. The conclusion is that there is not a clear benefit for it and the required invested time and efforts would be too high. For more explanation, read the minutes. permalink: /sips/:title.html --- @@ -26,11 +26,11 @@ So, here is the proposal (for Scala 2.10): if expression then expression [else expression] -3. At some point in the future (there’s no rush) we could deprecate the form +3. At some point in the future (there’s no rush) we could deprecate the form if (expression) expression else expression - and then remove it. + and then remove it. Once we have dealt with if, we should do the same thing with while, do-while and for. @@ -61,9 +61,9 @@ For while loops: ? I.e. a `do-while` loop inside an old-style `while` loop? Here’s a possible migration strategy. -2. In Scala 2.10: Introduce +2. In Scala 2.10: Introduce - while expression1 do expression2 + while expression1 do expression2 where `expression1` is not allowed to have parentheses at the outermost level (there’s no need to have them anyway). Also, emit a deprecation warning if the compiler comes across a do-while nested directly in an old-style while: @@ -83,7 +83,7 @@ For while loops: For-loops and for expressions can be handled similarly: -1. Allow +1. Allow for enumerators yield expression diff --git a/_sips/sips/2012-01-21-futures-promises.md b/_sips/sips/2012-01-21-futures-promises.md index 8158cfe598..38a41f4f75 100644 --- a/_sips/sips/2012-01-21-futures-promises.md +++ b/_sips/sips/2012-01-21-futures-promises.md @@ -723,8 +723,8 @@ Examples: [1]: http://www.microsoft.com/download/en/details.aspx?id=19957 "NETAsync" [2]: http://twitter.github.com/scala_school/finagle.html "Finagle" - [3]: http://akka.io/docs/akka/2.0-M2/scala/futures.html "AkkaFutures" - [4]: http://www.scala-lang.org/api/current/scala/actors/Futures$.html "SActorsFutures" + [3]: https://doc.akka.io/docs/akka/current/futures.html "AkkaFutures" + [4]: http://www.scala-lang.org/api/2.9.3/scala/actors/Future.html "SActorsFutures" [5]: http://code.google.com/p/scalaz/ "Scalaz" diff --git a/_sips/sips/2012-03-09-self-cleaning-macros.md b/_sips/sips/2012-03-09-self-cleaning-macros.md index 1ceccd3806..65572f5d05 100644 --- a/_sips/sips/2012-03-09-self-cleaning-macros.md +++ b/_sips/sips/2012-03-09-self-cleaning-macros.md @@ -3,7 +3,7 @@ layout: sip title: SIP-16 - Self-cleaning Macros vote-status: rejected -vote-text: The proposal is rejected unanimously because Scala Meta, the successor metaprogramming tool, is coming soon. For more explanation, read the minutes. +vote-text: The proposal is rejected unanimously because Scala Meta, the successor metaprogramming tool, is coming soon. For more explanation, read the minutes. permalink: /sips/:title.html --- diff --git a/_sips/sips/2013-05-31-improved-lazy-val-initialization.md b/_sips/sips/2013-05-31-improved-lazy-val-initialization.md index 7b3d430d48..cdffa3c486 100644 --- a/_sips/sips/2013-05-31-improved-lazy-val-initialization.md +++ b/_sips/sips/2013-05-31-improved-lazy-val-initialization.md @@ -699,7 +699,7 @@ Both Dotty and released Scala 2.12 already implement "Elegant Local lazy vals". ### Unsafe ### The proposed version, V6 relies on `sun.misc.Unsafe` in order to implement it's behaviour. While `sun.misc.Unsafe` will remain availabe in Java9 there's an intention to deprecate it and replace it with VarHandles.\[[20][20]\]. -The proposed version V6 can be implemented with using functionality present in Var Handles. +The proposed version V6 can be implemented with using functionality present in Var Handles. ## Acknowledgements ## @@ -744,7 +744,7 @@ We would like to thank Peter Levart and the other members of the concurrency-int [14]: https://github.com/scala/scala-dev/issues/133 [15]: http://scala-lang.org/blog/2016/10/24/scalafix.html [16]: https://github.com/scala/docs.scala-lang/pull/491 - [17]: https://github.com/lampepfl/dotty/blob/master/src/dotty/runtime/LazyHolders.scala + [17]: https://github.com/lampepfl/dotty/blob/f92f278ab686ab218e841082dcb026c6c8ef89b7/library/src/dotty/runtime/LazyHolders.scala [18]: https://d-d.me/tnc/30/lazy-mem/report/#config=%7B%22filterConfig%22%3A%7B%22curves%22%3A%5B%22-1%22%2C%220%22%2C%221%22%2C%222%22%2C%223%22%2C%224%22%2C%225%22%2C%226%22%2C%227%22%2C%228%22%5D%2C%22order%22%3A%5B%22param-size%22%2C%22date%22%5D%2C%22filters%22%3A%5B%5B%221000000%22%2C%222000000%22%2C%223000000%22%2C%224000000%22%2C%225000000%22%5D%2C%5B%221477396691000%22%5D%5D%7D%2C%22chartConfig%22%3A%7B%22type%22%3A0%2C%22showCI%22%3Afalse%7D%7D [19]: https://d-d.me/tnc/30/lazy-sip-perf/report/#config=%7B%22filterConfig%22%3A%7B%22curves%22%3A%5B%2216%22%2C%2217%22%2C%2218%22%2C%2219%22%2C%2221%22%2C%2222%22%2C%2223%22%5D%2C%22order%22%3A%5B%22param-size%22%2C%22date%22%5D%2C%22filters%22%3A%5B%5B%22100000%22%2C%22300000%22%2C%22500000%22%2C%221000000%22%2C%223000000%22%2C%225000000%22%5D%2C%5B%221477397877000%22%5D%5D%7D%2C%22chartConfig%22%3A%7B%22type%22%3A0%2C%22showCI%22%3Afalse%7D%7D [20]: http://openjdk.java.net/jeps/193 diff --git a/_sips/sips/2013-06-30-async.md b/_sips/sips/2013-06-30-async.md index f051bfe986..22d8eb48f1 100644 --- a/_sips/sips/2013-06-30-async.md +++ b/_sips/sips/2013-06-30-async.md @@ -4,7 +4,7 @@ discourse: true title: SIP-22 - Async vote-status: dormant -vote-text: Authors have marked this proposal as dormant. Details in the implementation need to be figured out. Check July 2016's minutes. +vote-text: Authors have marked this proposal as dormant. Details in the implementation need to be figured out. Check July 2016's minutes. permalink: /sips/:title.html --- @@ -121,12 +121,12 @@ the state machine. The class contains: ### Example - val future = async { - val f1 = async { true } - val x = 1 - def inc(t: Int) = t + x - val t = 0 - val f2 = async { 42 } + val future = async { + val f1 = async { true } + val x = 1 + def inc(t: Int) = t + x + val t = 0 + val f2 = async { 42 } if (await(f1)) await(f2) else { val z = 1; inc(t + z) } } diff --git a/_sips/sips/2016-01-11-static-members.md b/_sips/sips/2016-01-11-static-members.md index 22006c99c7..d7f3e83eb8 100644 --- a/_sips/sips/2016-01-11-static-members.md +++ b/_sips/sips/2016-01-11-static-members.md @@ -24,7 +24,7 @@ For example, classes extending `android.os.Parcelable` are required to have a st Another example is using an [`AtomicReferenceFieldUpdater`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.html). -On the JavaScript side, one example is [Relay Route Definitions](https://facebook.github.io/relay/docs/guides-routes.html), whose subclasses must define static fields such as `queries`. +On the JavaScript side, one example is [Relay Route Definitions](https://facebook.github.io/relay/docs/en/routing.html), whose subclasses must define static fields such as `queries`. Static methods and fields for JavaScript classes are one of the very few things (if not the only thing) that Scala.js "cannot do" at the moment, at least not declaratively. ## Overview ## diff --git a/_sips/sips/2016-09-09-inline-meta.md b/_sips/sips/2016-09-09-inline-meta.md index cd121f6389..a58cde17f8 100644 --- a/_sips/sips/2016-09-09-inline-meta.md +++ b/_sips/sips/2016-09-09-inline-meta.md @@ -1016,7 +1016,7 @@ mandated by the SIP process. [Materialization]: http://docs.scala-lang.org/overviews/macros/implicits.html [SbtMacroSupport]: https://github.com/sbt/sbt/issues/1729 [AnonymousTypeProviders]: http://docs.scala-lang.org/overviews/macros/typeproviders.html#anonymous-type-providers -[ExtractorMacros]: http://docs.scala-lang.org/overviews/macros/extractors +[ExtractorMacros]: https://docs.scala-lang.org/overviews/macros/extractors.html [AnnotationsTypecheck]: https://github.com/scalamacros/paradise/issues/75 [FeedbackSection]: #feedback [FeedbackWebsite]: http://gitter.im/scalameta/sips diff --git a/_sips/sips/2017-01-13-binary-compatibility.md b/_sips/sips/2017-01-13-binary-compatibility.md index cc3837b2b0..d156a4cc8b 100644 --- a/_sips/sips/2017-01-13-binary-compatibility.md +++ b/_sips/sips/2017-01-13-binary-compatibility.md @@ -53,7 +53,7 @@ As defined by the JVM spec\[[4]\]: which may affect all subclasses of this class leading to a runtime linkage failure. In this document we use the term `Public API` to refer both to methods and fields defined as `ACC_PUBLIC` and `ACC_PROTECTED`. - Changes do binary descriptors of Public API may lead to runtime linkage failures. + Changes do binary descriptors of Public API may lead to runtime linkage failures. * ##### Binary compatibility @@ -90,7 +90,7 @@ Examples: sbt additionally compiles on demand the compiler bridge, which implements this Java interface. 2. Dotty\[[7]\] currently uses java defined interfaces as public API for IntelliJ in order to ensure binary compatibility. -These interfaces can be replaced by `@stableABI` annotated traits to reach the same goal. +These interfaces can be replaced by `@stableABI` annotated traits to reach the same goal. ## Design Guidelines `@stableABI` is a feature which is supposed to be used by a small subset of the ecosystem to be binary compatible across major versions of Scala. @@ -203,8 +203,8 @@ and only return `@stableABI` values, we believe that all-or-nothing system will Because of this we propose to emmit warnings in those cases: - non-`@stableABI` value is returned from a method or field defined inside a `@stableABI` class or trait; - - an invocation to a method not-defined inside a `@stableABI` class is used in - implementation of a method or a field initializer inside a `@stableABI` class or trait. + - an invocation to a method not-defined inside a `@stableABI` class is used in + implementation of a method or a field initializer inside a `@stableABI` class or trait. Those warnings can be suppressed using an `@unchecked` annotations or made fatal using `+Xfatal-warnings`. @@ -241,7 +241,7 @@ Multiple features of Scala, most notably lazy vals and traits, have been compile making porting existing compiled bytecode across versions very hard. MiMa will complain retroactively that the new version is incompatible with the old one. `@stableABI` will instead indicate at compile time that the old version used features whose encoding is prone to change. -This provides early guidance and warning when designing long-living APIs before they are publicly released. +This provides early guidance and warning when designing long-living APIs before they are publicly released. ## Compilation scheme ## No modification of typer or any existing phase is planned. The current proposed scheme introduces a late phase that runs before the very bytecode emission that checks that: @@ -295,4 +295,5 @@ Thus, the authors of this SIP has decided not to allow default methods in the [5]: http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.6-200-A.1 "JVM access flags" [6]: http://www.scala-lang.org/files/archive/spec/2.11/05-classes-and-objects.html#modifiers "Scala AccessModifiers" [7]: https://github.com/lampepfl/dotty/tree/master/interfaces/src/dotty/tools/dotc/interfaces "Dotty interfaces" -[8]: https://github.com/sbt/zinc/tree/1.0/internal/compiler-interface/src/main/java/xsbti "zinc interfaces" +[8]: https://github.com/sbt/zinc/tree/v1.0.0/internal/compiler-interface/src/main/java/xsbti "zinc interfaces" + diff --git a/_sips/sips/2017-09-20-opaque-types.md b/_sips/sips/2017-09-20-opaque-types.md index 903750bb23..988bd81907 100644 --- a/_sips/sips/2017-09-20-opaque-types.md +++ b/_sips/sips/2017-09-20-opaque-types.md @@ -37,7 +37,7 @@ Some use cases for opaque types are: * Classes representing different entities with the same underlying type, such as `Id` and `Password` being defined in terms of `String`. -We expand on all these points in our [Motivation](motivation) section. +We expand on all these points in our motivation section. For a definition of boxing and previous state-of-the-art, we recommend reading [SIP-15]. @@ -323,7 +323,7 @@ qualifies the type equivalence for opaque types: > If `t` is defined by an opaque type `opaque type t = T`, then `t` is not equivalent to `T` unless `t` occurs in the template of the opaque type companion. -In the [Implementation notes](implementation-notes), we explain how this can be achieved in the +In the Implementation notes, we explain how this can be achieved in the implementation. ### Opaque type companion @@ -465,12 +465,12 @@ opaque type `Fix`: ```scala package object fixed { opaque type Fix[F_]] = F[Fix[F]] - + object Fix { def fix[F[_]](unfixed: F[Fix[F]]): Fix[F] = unfixed def unfix[F[_]](fixed: Fix[F]): F[Fix[F]] = fixed } - + sealed abstract class TreeU[R] type Tree = Fix[TreeU] @@ -514,10 +514,10 @@ bounding the underlying type (`A`) with `AnyRef`. ```scala package object nullable { opaque type Nullable[A <: AnyRef] = A - + object Nullable { def apply[A <: AnyRef](a: A): Nullable[A] = a - + implicit class NullableOps[A <: AnyRef](na: Nullable[A]) { def exists(p: A => Boolean): Boolean = na != null && p(na) @@ -692,7 +692,7 @@ package object prob { } def asDouble(p: Probability): Double = p - + val Never: Probability = 0.0 val CoinToss: Probability = 0.5 val Certain: Probability = 1.0 diff --git a/_style/index.md b/_style/index.md index 1b12cbf093..29ae8d16b5 100644 --- a/_style/index.md +++ b/_style/index.md @@ -31,7 +31,7 @@ This document is intended to outline some basic Scala stylistic guidelines which - [Annotations](types.html#annotations) - [Ascription](types.html#ascription) - [Functions](types.html#functions) - - [Arity-1](types.html#arity-1) + - [Arity-1](types.html) - [Structural Types](types.html#structural-types) - [Nested Blocks](nested-blocks.html) - [Curly Braces](nested-blocks.html#curly-braces) @@ -43,7 +43,7 @@ This document is intended to outline some basic Scala stylistic guidelines which - [Modifiers](declarations.html#modifiers) - [Body](declarations.html#body) - [Multiple Parameter Lists](declarations.html#multiple-parameter-lists) - - [Higher-Order Functions](declarations.html#higher-order-functions) + - [Higher-Order Functions](declarations.html) - [Fields](declarations.html#fields) - [Function Values](declarations.html#function-values) - [Spacing](declarations.html#spacing) @@ -55,10 +55,10 @@ This document is intended to outline some basic Scala stylistic guidelines which - [Method Invocation](method-invocation.html) - [Arity-0](method-invocation.html#arity-0) - [Infix Notation](method-invocation.html#infix-notation) - - [Postfix Notation](method-invocation.html#posfix-notation) - - [Arity-1](method-invocation.html#arity-1) - - [Higher-Order Functions](method-invocation.html#higher-order-functions) - - [Symbolic methods/Operators](method-invocation.html#symbolic-methodsoperators) + - [Postfix Notation](method-invocation.html) + - [Arity-1](method-invocation.html) + - [Higher-Order Functions](method-invocation.html) + - [Symbolic methods/Operators](method-invocation.html) - [Files](files.html) - [Multi-Unit Files](files.html#multi-unit-files) - [Scaladoc](scaladoc.html) diff --git a/_tour/abstract-types.md b/_tour/abstract-types.md index f5e30f7f5a..61b7651a4c 100644 --- a/_tour/abstract-types.md +++ b/_tour/abstract-types.md @@ -1,4 +1,4 @@ - +--- layout: tour title: Abstract Types diff --git a/_tour/automatic-closures.md b/_tour/automatic-closures.md new file mode 100644 index 0000000000..37b82524ef --- /dev/null +++ b/_tour/automatic-closures.md @@ -0,0 +1,61 @@ +--- +layout: tour +title: Automatic Type-Dependent Closure Construction + +discourse: true + +partof: scala-tour +--- + +Scala allows parameterless function names as parameters of methods. When such a method is called, the actual parameters for parameterless function names are not evaluated and a nullary function is passed instead which encapsulates the computation of the corresponding parameter (so-called *call-by-name* evalutation). + +The following code demonstrates this mechanism: + + object TargetTest1 extends Application { + def whileLoop(cond: => Boolean)(body: => Unit): Unit = + if (cond) { + body + whileLoop(cond)(body) + } + var i = 10 + whileLoop (i > 0) { + println(i) + i -= 1 + } + } + +The function whileLoop takes two parameters `cond` and `body`. When the function is applied, the actual parameters do not get evaluated. But whenever the formal parameters are used in the body of `whileLoop`, the implicitly created nullary functions will be evaluated instead. Thus, our method `whileLoop` implements a Java-like while-loop with a recursive implementation scheme. + +We can combine the use of [infix/postfix operators](operators.html) with this mechanism to create more complex statements (with a nice syntax). + +Here is the implementation of a loop-unless statement: + + object TargetTest2 extends Application { + def loop(body: => Unit): LoopUnlessCond = + new LoopUnlessCond(body) + protected class LoopUnlessCond(body: => Unit) { + def unless(cond: => Boolean) { + body + if (!cond) unless(cond) + } + } + var i = 10 + loop { + println("i = " + i) + i -= 1 + } unless (i == 0) + } +The `loop` function just accepts a body of a loop and returns an instance of class `LoopUnlessCond` (which encapsulates this body object). Note that the body didn't get evaluated yet. Class `LoopUnlessCond` has a method `unless` which we can use as a *infix operator*. This way, we achieve a quite natural syntax for our new loop: `loop { < stats > } unless ( < cond > )`. + +Here's the output when `TargetTest2` gets executed: + + i = 10 + i = 9 + i = 8 + i = 7 + i = 6 + i = 5 + i = 4 + i = 3 + i = 2 + i = 1 diff --git a/_tour/polymorphic-methods.md b/_tour/polymorphic-methods.md index 03a2e814b2..e7c68370e8 100644 --- a/_tour/polymorphic-methods.md +++ b/_tour/polymorphic-methods.md @@ -20,11 +20,12 @@ Methods in Scala can be parameterized by type as well as value. The syntax is si Here is an example: ```tut -def listOfDuplicates[A](x: A, length: Int): List[A] = +def listOfDuplicates[A](x: A, length: Int): List[A] = { if (length < 1) Nil else x :: listOfDuplicates(x, length - 1) +} println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3) println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La) ``` diff --git a/_zh-cn/overviews/core/actors-migration-guide.md b/_zh-cn/overviews/core/actors-migration-guide.md index 0034ebe8ad..a7c6b76a17 100644 --- a/_zh-cn/overviews/core/actors-migration-guide.md +++ b/_zh-cn/overviews/core/actors-migration-guide.md @@ -41,7 +41,7 @@ discourse: false 在Scal 2.10.0 actors 是在[Scala distribution](http://www.scala-lang.org/downloads)中作为一个单独包(scala-actors.jar)存在的,并且他们的接口已被弃用。这种分布也包含在Akka actors的akka-actor.jar里。AMK同时存在Scala actors 和 akka-actor.jar之中。未来的主要版本的Scala将不包含Scala actors和AMK。 -开始迁移,用户需要添加scala-actors.jar和scala-actors-migration.jar来构建他们的项目。添加scala-actors.jar和scala-actors-migration.jar允许使用下面描述的AMK。这些jar位于[Scala Tools](https://oss.sonatype.org/content/groups/scala-tools/org/scala-lang/)库和[Scala distribution](http://www.scala-lang.org/downloads)库中。 +开始迁移,用户需要添加scala-actors.jar和scala-actors-migration.jar来构建他们的项目。添加scala-actors.jar和scala-actors-migration.jar允许使用下面描述的AMK。这些jar位于Scala Tools库和[Scala distribution](http://www.scala-lang.org/downloads)库中。 ### 一步一步来迁移 @@ -83,7 +83,7 @@ Scala actors库提供了公共访问多个类型的actors。他们被组织在 actor实例的转换规则(以下规则需要import scala.actors.migration._): -1. 构造器调用实例化 +1. 构造器调用实例化 val myActor = new MyActor(arg1, arg2) myActor.start() diff --git a/_zh-cn/overviews/parallel-collections/concrete-parallel-collections.md b/_zh-cn/overviews/parallel-collections/concrete-parallel-collections.md index 793beebcda..9aac14f0d3 100644 --- a/_zh-cn/overviews/parallel-collections/concrete-parallel-collections.md +++ b/_zh-cn/overviews/parallel-collections/concrete-parallel-collections.md @@ -24,7 +24,7 @@ language: zh-cn scala> pa map (x => (x - 1) / 2) res1: scala.collection.parallel.mutable.ParArray[Int] = ParArray(0, 1, 2, 3, 4, 5, 6, 7,... -在内部,分离一个并行数组[分离器](http://docs.scala-lang.org/overviews/parallel-collections/architecture.html#core_abstractions)相当于使用它们的下标迭代器更新来创建两个分离器。[组合](http://docs.scala-lang.org/overviews/parallel-collections/architecture.html#core_abstractions)稍微负责一点。因为大多数的分离方法(如:flatmap, filter, takeWhile等)我们不能预先知道元素的个数(或者数组的大小),每一次组合本质上来说是一个数组缓冲区的一种变量根据分摊时间来进行加减的操作。不同的处理器进行元素相加操作,对每个独立并列数组进行组合,然后根据其内部连结在再进行组合。在并行数组中的基础数组只有在知道元素的总数之后才能被分配和填充。基于此,变换方法比存取方法要稍微复杂一些。另外,请注意,最终数组分配在JVM上的顺序进行,如果映射操作本身是很便宜,这可以被证明是一个序列瓶颈。 +在内部,分离一个并行数组[分离器](http://docs.scala-lang.org/overviews/parallel-collections/architecture.html)相当于使用它们的下标迭代器更新来创建两个分离器。[组合](http://docs.scala-lang.org/overviews/parallel-collections/architecture.html)稍微负责一点。因为大多数的分离方法(如:flatmap, filter, takeWhile等)我们不能预先知道元素的个数(或者数组的大小),每一次组合本质上来说是一个数组缓冲区的一种变量根据分摊时间来进行加减的操作。不同的处理器进行元素相加操作,对每个独立并列数组进行组合,然后根据其内部连结在再进行组合。在并行数组中的基础数组只有在知道元素的总数之后才能被分配和填充。基于此,变换方法比存取方法要稍微复杂一些。另外,请注意,最终数组分配在JVM上的顺序进行,如果映射操作本身是很便宜,这可以被证明是一个序列瓶颈。 通过调用seq方法,并行数组(parallel arrays)被转换为对应的顺序容器(sequential collections) ArraySeq。这种转换是非常高效的,因为新创建的ArraySeq 底层是通过并行数组(parallel arrays)获得的。 diff --git a/contribute.md b/contribute.md index 6d8866e325..9f4692f679 100644 --- a/contribute.md +++ b/contribute.md @@ -37,7 +37,7 @@ This documentation repository is open-source, it lives in [github repository](ht It's statically generated from [Markdown](http://en.wikipedia.org/wiki/Markdown) source using [Jekyll](https://github.com/mojombo/jekyll), and hosted on [GitHub Pages](http://pages.github.com/). This workflow was chosen so as to make it as easy as possible for core committers and the community alike to produce HTML documentation, and as easy as possible to publish it in a central location. -The markdown syntax being used supports [Maruku](http://maruku.rubyforge.org/maruku.html) extensions, and has automatic syntax highlighting, without the need for any tags. +The markdown syntax being used supports [Maruku](https://github.com/bhollis/maruku) extensions, and has automatic syntax highlighting, without the need for any tags. Additionally [tut](https://github.com/tpolecat/tut) is used during pull requests to validate Scala code blocks. To use this feature you must use the backtick notation as documented by tut. Note that only validation is done. The output files from tut are not used in the building of the tutorial. Either use `tut` or `tut:fail` for your code blocks. diff --git a/scripts/ci.sh b/scripts/ci.sh index 13e23eb863..b0a3d2be09 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -1,6 +1,15 @@ -#!/bin/bash - +#!/bin/bash + . /usr/local/rvm/scripts/rvm + +set -eux + bundle install ./scripts/run-tut.sh rm -r tut-tmp bundle exec jekyll build + +# Checking for docs.scala-lang/blob/master leads to a chicken and egg problem because of the edit links of new pages. +bundle exec htmlproofer ./_site/ --only-4xx --empty-alt-ignore --allow-hash-href --url-ignore '/https://github.com/scala/docs.scala-lang/blob/master/.*/' + +exit 0 diff --git a/scripts/run-tut.sh b/scripts/run-tut.sh index 24eb038eea..c8094071bd 100755 --- a/scripts/run-tut.sh +++ b/scripts/run-tut.sh @@ -1,5 +1,9 @@ #!/bin/bash -COURSIER_CLASSPATH="$(coursier fetch -p com.chuusai:shapeless_2.11:2.3.1 org.scala-lang.modules::scala-xml:1.0.3)" +set -eux + +COURSIER_CLASSPATH="$(coursier fetch -p org.scala-lang.modules::scala-xml:1.0.3)" coursier launch -r "https://dl.bintray.com/tpolecat/maven/" org.tpolecat:tut-core_2.11:0.4.4 -- . tut-tmp '.*\.md$' -classpath "$COURSIER_CLASSPATH" -Xfatal-warnings -feature + +exit 0