diff --git a/.bundle/config b/.bundle/config
deleted file mode 100644
index 9bc01b4c32..0000000000
--- a/.bundle/config
+++ /dev/null
@@ -1,3 +0,0 @@
----
-BUNDLE_PATH: "vendor/bundle"
-BUNDLE_DISABLE_SHARED_GEMS: "true"
diff --git a/.drone.yml b/.drone.yml
deleted file mode 100644
index d36025ce89..0000000000
--- a/.drone.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-pipeline:
- build:
- image: scalacenter/scala-rvm-jvm-coursier:2.0
- pull: true
- commands:
- - ./scripts/ci.sh
diff --git a/.drone.yml.sig b/.drone.yml.sig
deleted file mode 100644
index 8240a38b07..0000000000
--- a/.drone.yml.sig
+++ /dev/null
@@ -1 +0,0 @@
-eyJhbGciOiJIUzI1NiJ9.cGlwZWxpbmU6CiAgYnVpbGQ6CiAgICBpbWFnZTogamRrLXJ2bS1jb3Vyc2llcjpsYXRlc3QKICAgIHB1bGw6IHRydWUKICAgIGNvbW1hbmRzOgogICAgICAtIHNvdXJjZSB-Ly5wcm9maWxlCiAgICAgIC0gYnVuZGxlIGluc3RhbGwKICAgICAgLSAuL3NjcmlwdHMvcnVuLXR1dC5zaAogICAgICAtIHJtIC1yIHR1dC10bXAKICAgICAgLSBidW5kbGUgZXhlYyBqZWt5bGwgYnVpbGQK.7Rp37FEwRqAo85EdFYZh1PoyU8mxpFdEnpchWaQkHCc
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 0000000000..ce1bb0f48b
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1 @@
+/_ja @scala/docs-ja
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000000..f48b4ada51
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,11 @@
+version: 2
+updates:
+- package-ecosystem: bundler
+ directory: "/"
+ schedule:
+ interval: daily
+ open-pull-requests-limit: 10
+ ignore:
+ - dependency-name: html-proofer
+ versions:
+ - "> 3.15.3"
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000000..e56f07a0ab
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,33 @@
+name: Build
+on: [push, pull_request]
+jobs:
+ build:
+ runs-on: ubuntu-22.04
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Ruby
+ uses: ruby/setup-ruby@v1
+ with:
+ ruby-version: 3.2.6
+ bundler-cache: true
+ - name: Set up coursier
+ uses: coursier/setup-action@v1.3.5
+ with:
+ jvm: adopt:11
+ - name: Run mdoc
+ run: |
+ ./scripts/run-mdoc.sh
+ rm -r /tmp/mdoc-out/
+ - name: Jekyll build
+ run: bundle exec jekyll build
+ - name: HTMLProofer
+ run: |
+ # # Checking for docs.scala-lang/blob/main leads to a chicken and egg problem because of the edit links of new pages.
+ bundle exec htmlproofer ./_site/\
+ --only-4xx\
+ --ignore-status-codes "400,401,403,429"\
+ --ignore-empty-alt\
+ --allow-hash-href\
+ --no-enforce-https\
+ --ignore-urls '/https://github.com/scala/,/www.oracle.com/'
+
diff --git a/.gitignore b/.gitignore
index c73823b558..055aee462d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,5 +8,5 @@ _site
vendor/bundle
.idea/
/coursier
-/tut-tmp/
.sass-cache/
+.jekyll-cache/
\ No newline at end of file
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index 948de8e719..0511f2126d 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -1,78 +1,7 @@
-## Scala Code of Conduct
+all repositories in these organizations:
-We are committed to providing a friendly, safe and welcoming environment for
-all, regardless of level of experience, gender, gender identity and expression,
-sexual orientation, disability, personal appearance, body size, race, ethnicity,
-age, religion, nationality, or other such characteristics.
+* [scala](https://github.com/scala)
+* [scalacenter](https://github.com/scalacenter)
+* [lampepfl](https://github.com/lampepfl)
-### Our Standards
-
-**Whether you’re a regular contributor or a newcomer, we care about making this community a welcoming and safe place for you and we’ve got your back.**
-
-As a member of the community, you agree to the following:
-
-**Encouraged:**
-
-- Be kind and courteous.
-- Respect differences of opinion and remember that every design or implementation choice carries a trade-off and numerous costs. There is seldom a single right answer.
-- Remember that everyone was new to Scala at some point. We want to encourage newcomers to join our community and learn the Scala language and ecosystem. Assume competence.
-- Show empathy towards other community members.
-
-**Discouraged:**
-
-- Keep unstructured critique to a minimum. We encourage sharing ideas and perspectives, so please ensure that your feedback is constructive and relevant. If you have solid ideas you want to experiment with, make a fork and see how it works.
-- Avoid aggressive and micro-aggressive behavior, such as unconstructive criticism, providing corrections that do not improve the conversation (sometimes referred to as "well actually"s), repeatedly interrupting or talking over someone else, feigning surprise at someone’s lack of knowledge or awareness about a topic, or subtle prejudice (for example, comments like “That’s so easy my grandmother could do it.”). For more examples of this kind of behavior, [see the Recurse Center's user manual](https://www.recurse.com/manual#sec-environment).
-- We will exclude you from interaction if you insult, demean or harass anyone. The term “Harassment” includes “Unacceptable Behavior” described in the [Citizen Code of Conduct](http://citizencodeofconduct.org/). **In particular, we don’t tolerate behavior that excludes people in socially marginalized groups.**
-- Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member's behavior, please contact one of the [moderators](https://contributors.scala-lang.org/about) or any member of the [Scala Center](http://scala.epfl.ch/) immediately.
-- Likewise any spamming, trolling, flaming, baiting or other attention-stealing behaviour is not welcome.
-
-### Moderation
-
-These are the policies for upholding our community’s standards of conduct. If
-you feel that a thread needs moderation, please contact anyone on the
-[moderation team](https://contributors.scala-lang.org/about), or any employee of
-the [Scala Center](https://scala.epfl.ch/).
-
-- Remarks that violate the above code of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.)
-- Moderators will warn users who make remarks inconsistent with the above code of conduct.
-- If the warning is unheeded, the user will be “kicked,” i.e., kicked out of the communication channel to cool off.
-- If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded.
-- Moderators may choose at their discretion to un-ban the user if it was a first offense and they if they make suitable amends with the offended party.
-- If you think a ban is unjustified, please take it up with that moderator, or with a different moderator, in private. Complaints about bans in-channel are not allowed.
-- Moderators are held to a higher standard than other community members. If a moderator acts inappropriately, they should expect less leeway than others.
-
-In the Scala community we strive to go the extra step to look out for each
-other. Don’t just aim to be technically unimpeachable; try to be your best self.
-In particular, avoid exacerbating offensive or sensitive issues, particularly if
-they’re off-topic; this all too often leads to unnecessary fights, hurt
-feelings, and damaged trust; worse, it can drive people away from the community
-entirely.
-
-If someone takes issue with something you said or did, resist the urge to be
-defensive. Rather, stop the offending behavior, apologize, and be sensitive
-thereafter. Even if you feel you were misinterpreted or unfairly accused,
-chances are good there was something you could’ve communicated better — remember
-that it’s your responsibility to make your fellow Scala developers comfortable.
-We are all here first and foremost because we want to talk about cool
-technology, and everyone wants to get along in doing so. People are generally
-eager to assume good intent and forgive.
-
-### Domain
-
-The enforcement policies listed above apply to all official Scala channels:
-mailing lists, GitHub repositories and Gitter channels under scala and
-scalacenter, Discourse, and Scala Center venues and hackathons. For other
-projects adopting the Scala Code of Conduct, please contact the maintainers of
-those projects for enforcement. If you wish to use this code of conduct for your
-own project, consider explicitly mentioning your moderation policy or making a
-copy with your own moderation policy so as to avoid confusion.
-
-### Credits
-
-Adapted from and/or inspired by multiple successful Codes of Conduct, including:
-
-* [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html)
-* [The Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling)
-* [The Contributor Covenant v1.4.0](http://contributor-covenant.org/version/1/4/)
-* [The Recurse Center's User Manual](https://www.recurse.com/manual#sec-environment)
-* [The 18F Code of Conduct](https://18f.gsa.gov/code-of-conduct/)
\ No newline at end of file
+are covered by the Scala Code of Conduct: https://scala-lang.org/conduct/
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000..b2bbc255f9
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,12 @@
+FROM ruby:3.2.6
+
+RUN gem install bundler:2.6.5
+
+WORKDIR /srv/jekyll
+
+COPY Gemfile .
+COPY Gemfile.lock .
+
+RUN echo -n "bundle version: " && bundle --version
+RUN chmod u+s /bin/chown
+RUN bundle install
diff --git a/Gemfile b/Gemfile
index a0b87e6bb8..31cb37fbea 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,14 +1,6 @@
source 'https://rubygems.org'
-gem 'jekyll-redirect-from'
-gem 'jekyll-scalafiddle'
+gem 'github-pages'
+gem 'webrick'
+#
gem 'html-proofer'
-# gem 'html-proofer' # link-checking: bundle exec htmlproofer ./_site/ --only-4xx --empty-alt-ignore --allow-hash-href
-
-# group :jekyll_plugins do
-# gem 'hawkins'
-# end
-
-# ^ Useful for live reloading the site in your
-# browser during development. To use, uncomment
-# and do:
-# bundle exec jekyll liveserve --incremental
+# gem 'html-proofer' # link-checking: bundle exec htmlproofer ./_site/ --only-4xx --ignore-empty-alt=true --allow-hash-href=true
diff --git a/Gemfile.lock b/Gemfile.lock
index 4157511c7d..8088be3873 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,97 +1,333 @@
GEM
remote: https://rubygems.org/
specs:
- activesupport (5.2.0)
- concurrent-ruby (~> 1.0, >= 1.0.2)
- i18n (>= 0.7, < 2)
- minitest (~> 5.1)
- tzinfo (~> 1.1)
- addressable (2.5.2)
- public_suffix (>= 2.0.2, < 4.0)
+ Ascii85 (2.0.1)
+ activesupport (8.0.1)
+ base64
+ benchmark (>= 0.3)
+ bigdecimal
+ concurrent-ruby (~> 1.0, >= 1.3.1)
+ connection_pool (>= 2.2.5)
+ drb
+ i18n (>= 1.6, < 2)
+ logger (>= 1.4.2)
+ minitest (>= 5.1)
+ securerandom (>= 0.3)
+ tzinfo (~> 2.0, >= 2.0.5)
+ uri (>= 0.13.1)
+ addressable (2.8.7)
+ public_suffix (>= 2.0.2, < 7.0)
+ afm (0.2.2)
+ async (2.23.0)
+ console (~> 1.29)
+ fiber-annotation
+ io-event (~> 1.9)
+ metrics (~> 0.12)
+ traces (~> 0.15)
+ base64 (0.2.0)
+ benchmark (0.4.0)
+ bigdecimal (3.1.9)
+ coffee-script (2.4.1)
+ coffee-script-source
+ execjs
+ coffee-script-source (1.12.2)
colorator (1.1.0)
- colorize (0.8.1)
- concurrent-ruby (1.0.5)
- em-websocket (0.5.1)
+ commonmarker (0.23.11)
+ concurrent-ruby (1.3.5)
+ connection_pool (2.5.0)
+ console (1.29.3)
+ fiber-annotation
+ fiber-local (~> 1.1)
+ json
+ csv (3.3.2)
+ dnsruby (1.72.3)
+ base64 (~> 0.2.0)
+ simpleidn (~> 0.2.1)
+ drb (2.2.1)
+ em-websocket (0.5.3)
eventmachine (>= 0.12.9)
- http_parser.rb (~> 0.6.0)
- ethon (0.11.0)
- ffi (>= 1.3.0)
+ http_parser.rb (~> 0)
+ ethon (0.16.0)
+ ffi (>= 1.15.0)
eventmachine (1.2.7)
- ffi (1.9.25)
+ execjs (2.10.0)
+ faraday (2.12.2)
+ faraday-net_http (>= 2.0, < 3.5)
+ json
+ logger
+ faraday-net_http (3.4.0)
+ net-http (>= 0.5.0)
+ ffi (1.17.1-arm64-darwin)
+ ffi (1.17.1-x64-mingw-ucrt)
+ ffi (1.17.1-x86_64-linux-gnu)
+ fiber-annotation (0.2.0)
+ fiber-local (1.1.0)
+ fiber-storage
+ fiber-storage (1.0.0)
forwardable-extended (2.6.0)
- html-proofer (3.9.1)
- activesupport (>= 4.2, < 6.0)
+ gemoji (4.1.0)
+ github-pages (232)
+ github-pages-health-check (= 1.18.2)
+ jekyll (= 3.10.0)
+ jekyll-avatar (= 0.8.0)
+ jekyll-coffeescript (= 1.2.2)
+ jekyll-commonmark-ghpages (= 0.5.1)
+ jekyll-default-layout (= 0.1.5)
+ jekyll-feed (= 0.17.0)
+ jekyll-gist (= 1.5.0)
+ jekyll-github-metadata (= 2.16.1)
+ jekyll-include-cache (= 0.2.1)
+ jekyll-mentions (= 1.6.0)
+ jekyll-optional-front-matter (= 0.3.2)
+ jekyll-paginate (= 1.1.0)
+ jekyll-readme-index (= 0.3.0)
+ jekyll-redirect-from (= 0.16.0)
+ jekyll-relative-links (= 0.6.1)
+ jekyll-remote-theme (= 0.4.3)
+ jekyll-sass-converter (= 1.5.2)
+ jekyll-seo-tag (= 2.8.0)
+ jekyll-sitemap (= 1.4.0)
+ jekyll-swiss (= 1.0.0)
+ jekyll-theme-architect (= 0.2.0)
+ jekyll-theme-cayman (= 0.2.0)
+ jekyll-theme-dinky (= 0.2.0)
+ jekyll-theme-hacker (= 0.2.0)
+ jekyll-theme-leap-day (= 0.2.0)
+ jekyll-theme-merlot (= 0.2.0)
+ jekyll-theme-midnight (= 0.2.0)
+ jekyll-theme-minimal (= 0.2.0)
+ jekyll-theme-modernist (= 0.2.0)
+ jekyll-theme-primer (= 0.6.0)
+ jekyll-theme-slate (= 0.2.0)
+ jekyll-theme-tactile (= 0.2.0)
+ jekyll-theme-time-machine (= 0.2.0)
+ jekyll-titles-from-headings (= 0.5.3)
+ jemoji (= 0.13.0)
+ kramdown (= 2.4.0)
+ kramdown-parser-gfm (= 1.1.0)
+ liquid (= 4.0.4)
+ mercenary (~> 0.3)
+ minima (= 2.5.1)
+ nokogiri (>= 1.16.2, < 2.0)
+ rouge (= 3.30.0)
+ terminal-table (~> 1.4)
+ webrick (~> 1.8)
+ github-pages-health-check (1.18.2)
+ addressable (~> 2.3)
+ dnsruby (~> 1.60)
+ octokit (>= 4, < 8)
+ public_suffix (>= 3.0, < 6.0)
+ typhoeus (~> 1.3)
+ hashery (2.1.2)
+ html-pipeline (2.14.3)
+ activesupport (>= 2)
+ nokogiri (>= 1.4)
+ html-proofer (5.0.10)
addressable (~> 2.3)
- colorize (~> 0.8)
- mercenary (~> 0.3.2)
- nokogiri (~> 1.8.1)
- parallel (~> 1.3)
+ async (~> 2.1)
+ nokogiri (~> 1.13)
+ pdf-reader (~> 2.11)
+ rainbow (~> 3.0)
typhoeus (~> 1.3)
yell (~> 2.0)
- http_parser.rb (0.6.0)
- i18n (0.9.5)
+ zeitwerk (~> 2.5)
+ http_parser.rb (0.8.0)
+ i18n (1.14.7)
concurrent-ruby (~> 1.0)
- jekyll (3.8.3)
+ io-event (1.9.0)
+ jekyll (3.10.0)
addressable (~> 2.4)
colorator (~> 1.0)
+ csv (~> 3.0)
em-websocket (~> 0.5)
- i18n (~> 0.7)
+ i18n (>= 0.7, < 2)
jekyll-sass-converter (~> 1.0)
jekyll-watch (~> 2.0)
- kramdown (~> 1.14)
+ kramdown (>= 1.17, < 3)
liquid (~> 4.0)
mercenary (~> 0.3.3)
pathutil (~> 0.9)
rouge (>= 1.7, < 4)
safe_yaml (~> 1.0)
- jekyll-redirect-from (0.14.0)
- jekyll (~> 3.3)
+ webrick (>= 1.0)
+ jekyll-avatar (0.8.0)
+ jekyll (>= 3.0, < 5.0)
+ jekyll-coffeescript (1.2.2)
+ coffee-script (~> 2.2)
+ coffee-script-source (~> 1.12)
+ jekyll-commonmark (1.4.0)
+ commonmarker (~> 0.22)
+ jekyll-commonmark-ghpages (0.5.1)
+ commonmarker (>= 0.23.7, < 1.1.0)
+ jekyll (>= 3.9, < 4.0)
+ jekyll-commonmark (~> 1.4.0)
+ rouge (>= 2.0, < 5.0)
+ jekyll-default-layout (0.1.5)
+ jekyll (>= 3.0, < 5.0)
+ jekyll-feed (0.17.0)
+ jekyll (>= 3.7, < 5.0)
+ jekyll-gist (1.5.0)
+ octokit (~> 4.2)
+ jekyll-github-metadata (2.16.1)
+ jekyll (>= 3.4, < 5.0)
+ octokit (>= 4, < 7, != 4.4.0)
+ jekyll-include-cache (0.2.1)
+ jekyll (>= 3.7, < 5.0)
+ jekyll-mentions (1.6.0)
+ html-pipeline (~> 2.3)
+ jekyll (>= 3.7, < 5.0)
+ jekyll-optional-front-matter (0.3.2)
+ jekyll (>= 3.0, < 5.0)
+ jekyll-paginate (1.1.0)
+ jekyll-readme-index (0.3.0)
+ jekyll (>= 3.0, < 5.0)
+ jekyll-redirect-from (0.16.0)
+ jekyll (>= 3.3, < 5.0)
+ jekyll-relative-links (0.6.1)
+ jekyll (>= 3.3, < 5.0)
+ jekyll-remote-theme (0.4.3)
+ addressable (~> 2.0)
+ jekyll (>= 3.5, < 5.0)
+ jekyll-sass-converter (>= 1.0, <= 3.0.0, != 2.0.0)
+ rubyzip (>= 1.3.0, < 3.0)
jekyll-sass-converter (1.5.2)
sass (~> 3.4)
- jekyll-scalafiddle (1.0.1)
- jekyll (~> 3.0)
- jekyll-watch (2.0.0)
+ jekyll-seo-tag (2.8.0)
+ jekyll (>= 3.8, < 5.0)
+ jekyll-sitemap (1.4.0)
+ jekyll (>= 3.7, < 5.0)
+ jekyll-swiss (1.0.0)
+ jekyll-theme-architect (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-cayman (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-dinky (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-hacker (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-leap-day (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-merlot (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-midnight (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-minimal (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-modernist (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-primer (0.6.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-github-metadata (~> 2.9)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-slate (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-tactile (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-theme-time-machine (0.2.0)
+ jekyll (> 3.5, < 5.0)
+ jekyll-seo-tag (~> 2.0)
+ jekyll-titles-from-headings (0.5.3)
+ jekyll (>= 3.3, < 5.0)
+ jekyll-watch (2.2.1)
listen (~> 3.0)
- kramdown (1.17.0)
- liquid (4.0.0)
- listen (3.1.5)
- rb-fsevent (~> 0.9, >= 0.9.4)
- rb-inotify (~> 0.9, >= 0.9.7)
- ruby_dep (~> 1.2)
+ jemoji (0.13.0)
+ gemoji (>= 3, < 5)
+ html-pipeline (~> 2.2)
+ jekyll (>= 3.0, < 5.0)
+ json (2.10.2)
+ kramdown (2.4.0)
+ rexml
+ kramdown-parser-gfm (1.1.0)
+ kramdown (~> 2.0)
+ liquid (4.0.4)
+ listen (3.9.0)
+ rb-fsevent (~> 0.10, >= 0.10.3)
+ rb-inotify (~> 0.9, >= 0.9.10)
+ logger (1.6.6)
mercenary (0.3.6)
- mini_portile2 (2.3.0)
- minitest (5.11.3)
- nokogiri (1.8.4)
- mini_portile2 (~> 2.3.0)
- parallel (1.12.1)
- pathutil (0.16.1)
+ metrics (0.12.1)
+ minima (2.5.1)
+ jekyll (>= 3.5, < 5.0)
+ jekyll-feed (~> 0.9)
+ jekyll-seo-tag (~> 2.1)
+ minitest (5.25.4)
+ net-http (0.6.0)
+ uri
+ nokogiri (1.18.8-arm64-darwin)
+ racc (~> 1.4)
+ nokogiri (1.18.8-x64-mingw-ucrt)
+ racc (~> 1.4)
+ nokogiri (1.18.8-x86_64-linux-gnu)
+ racc (~> 1.4)
+ octokit (4.25.1)
+ faraday (>= 1, < 3)
+ sawyer (~> 0.9)
+ pathutil (0.16.2)
forwardable-extended (~> 2.6)
- public_suffix (3.0.2)
- rb-fsevent (0.10.3)
- rb-inotify (0.9.10)
- ffi (>= 0.5.0, < 2)
- rouge (3.1.1)
- ruby_dep (1.5.0)
- safe_yaml (1.0.4)
- sass (3.5.7)
+ pdf-reader (2.14.1)
+ Ascii85 (>= 1.0, < 3.0, != 2.0.0)
+ afm (~> 0.2.1)
+ hashery (~> 2.0)
+ ruby-rc4
+ ttfunk
+ public_suffix (5.1.1)
+ racc (1.8.1)
+ rainbow (3.1.1)
+ rb-fsevent (0.11.2)
+ rb-inotify (0.11.1)
+ ffi (~> 1.0)
+ rexml (3.4.1)
+ rouge (3.30.0)
+ ruby-rc4 (0.1.5)
+ rubyzip (2.4.1)
+ safe_yaml (1.0.5)
+ sass (3.7.4)
sass-listen (~> 4.0.0)
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 (1.3.0)
+ sawyer (0.9.2)
+ addressable (>= 2.3.5)
+ faraday (>= 0.17.3, < 3)
+ securerandom (0.4.1)
+ simpleidn (0.2.3)
+ terminal-table (1.8.0)
+ unicode-display_width (~> 1.1, >= 1.1.1)
+ traces (0.15.2)
+ ttfunk (1.8.0)
+ bigdecimal (~> 3.1)
+ typhoeus (1.4.1)
ethon (>= 0.9.0)
- tzinfo (1.2.5)
- thread_safe (~> 0.1)
- yell (2.0.7)
+ tzinfo (2.0.6)
+ concurrent-ruby (~> 1.0)
+ unicode-display_width (1.8.0)
+ uri (1.0.3)
+ webrick (1.9.1)
+ yell (2.2.2)
+ zeitwerk (2.7.2)
PLATFORMS
- ruby
+ arm64-darwin-22
+ arm64-darwin-23
+ arm64-darwin-24
+ x64-mingw-ucrt
+ x86_64-linux
DEPENDENCIES
+ github-pages
html-proofer
- jekyll-redirect-from
- jekyll-scalafiddle
+ webrick
BUNDLED WITH
- 1.16.2
+ 2.6.5
diff --git a/README.md b/README.md
index 6dccfec463..013a66267c 100644
--- a/README.md
+++ b/README.md
@@ -1,32 +1,62 @@
# Scala Documentation #
-[](https://platform-ci.scala-lang.org/scala/docs.scala-lang)
+[](https://github.com/scala/docs.scala-lang/actions/workflows/build.yml?query=branch%3Amain)
This repository contains the source for the Scala documentation website, as well as the source for "Scala Improvement Process" (SIP) documents.
+## Dependencies ##
+
+This site uses a Jekyll, a Ruby framework. You'll need Ruby and Bundler installed; see [Jekyll installation instructions](https://jekyllrb.com/docs/installation/) for the details.
+
## Quickstart ##
To build and view the site locally:
- gem install bundler
bundle install
bundle exec jekyll serve -I
+([Trouble on MacOS?](https://github.com/scala/docs.scala-lang/issues/1150))
+
For more details, read on.
+## Quickstart with Docker Compose ##
+
+You need to have [Docker Engine](https://docs.docker.com/engine/) and [Docker Compose](https://docs.docker.com/compose/) installed on your machine.
+Under macOS (Intel or Apple silicon), instead of installing [Docker Desktop](https://docs.docker.com/desktop/) you can also use [HomeBrew](https://brew.sh/) with [Colima](https://github.com/abiosoft/colima): `brew install colima docker docker-compose`.
+UID and GID environment variables are needed to avoid docker from writing files as root in your directory.
+By default, docker-compose will use the file docker-compose.yml which will build the website and serve it on 0.0.0.0:4000 .
+If you just need to build the website, add ```-f docker-compose_build-only.yml```
+
+```
+env UID="$(id -u)" GID="$(id -g)" docker-compose up
+```
+
+The generated site is available at `http://localhost:4000`.
+
+When the website dependencies change (the content of the `Gemfile`),
+you have to re-build the Docker image:
+
+```
+env UID="$(id -u)" GID="$(id -g)" docker-compose up --build
+```
+
+If you have problems with the Docker image or want to force the rebuild of the Docker image:
+```
+env UID="$(id -u)" GID="$(id -g)" docker-compose build --no-cache
+```
+
+
+For more details on the Docker option, see also [this issue](https://github.com/scala/docs.scala-lang/issues/1286).
+
## Contributing ##
-Please have a look at [http://docs.scala-lang.org/contribute.html](http://docs.scala-lang.org/contribute.html) before making a contribution.
+Please have a look at [Add New Guides/Tutorials](https://docs.scala-lang.org/contribute/add-guides.html) before making a contribution.
This document gives an overview of the type of documentation contained within the Scala Documentation repository and the repository's structure.
Small changes, or corrected typos will generally be pulled in right away. Large changes, like the addition of new documents, or the rewriting of
existing documents will be thoroughly reviewed-- please keep in mind that, generally, new documents must be very well-polished, complete, and maintained
in order to be accepted.
-## Dependencies ##
-
-This site uses a Jekyll, a Ruby framework. You'll need Ruby and Bundler installed; see [Jekyll installation instructions](http://jekyllrb.com/docs/installation/) for the details.
-
## Building & Viewing ##
cd into the directory where you cloned this repository, then install the required gems with `bundle install`. This will automatically put the gems into `./vendor/bundle`.
@@ -43,19 +73,19 @@ If you add `--watch` at the end of the command line above, Jekyll will automatic
If you get `incompatible encoding` errors when generating the site under Windows, then ensure that the
console in which you are running jekyll can work with UTF-8 characters. As described in the blog
-[Solving UTF problem with Jekyll on Windows](http://joseoncode.com/2011/11/27/solving-utf-problem-with-jekyll-on-windows/)
+[Solving UTF problem with Jekyll on Windows](https://joseoncode.com/2011/11/27/solving-utf-problem-with-jekyll-on-windows/)
you have to execute `chcp 65001`. This command is best added to the `jekyll.bat`-script.
## Markdown ##
-The markdown used in this site uses [kramdown](http://kramdown.gettalong.org/) extensions.
+The markdown used in this site uses [kramdown](https://kramdown.gettalong.org/) extensions.
### Markdown Editor for OSX ###
-There's a free markdown editor for OSX called [Mou](http://25.io/mou/). It's quite convenient to work with, and it generates the translated Markdown in real-time alongside of your editor window, as can be seen here:
+There's a free markdown editor for OSX called [MacDown](https://github.com/MacDownApp/macdown). It's quite convenient to work with, and it generates the translated Markdown in real-time alongside of your editor window, as can be seen here:
-
+
## License ##
-All documentation contained in this repository is licensed by EPFL under a Creative Commons Attribution-Share Alike 3.0 Unported license ("CC-BY-SA"), unless otherwise noted. By submitting a "pull request," or otherwise contributing to this repository, you implicitly agree to license your contribution under the above CC-BY-SA license. The source code of this website is licensed to EPFL under the [Scala License](http://www.scala-lang.org/node/146), unless otherwise noted.
+All documentation contained in this repository is licensed by EPFL under a Creative Commons Attribution-Share Alike 3.0 Unported license ("CC-BY-SA"), unless otherwise noted. By submitting a "pull request," or otherwise contributing to this repository, you implicitly agree to license your contribution under the above CC-BY-SA license. The source code of this website is licensed to EPFL under the [Scala License](https://www.scala-lang.org/node/146), unless otherwise noted.
diff --git a/_ba/cheatsheets/index.md b/_ba/cheatsheets/index.md
index 0a7e59790f..3ca8f61b70 100644
--- a/_ba/cheatsheets/index.md
+++ b/_ba/cheatsheets/index.md
@@ -1,11 +1,11 @@
---
layout: cheatsheet
-title: Scalacheat
+title: Scala Cheatsheet
partof: cheatsheet
by: Brendan O'Connor
-about: Zahvaljujući Brendan O'Connoru ovaj cheatsheet teži da bude kratki pregled sintakse Scale. Licenca pripada Brendan O'Connor-u, pod CC-BY-SA 3.0 licencom.
+about: Zahvaljujući Brendan O'Connoru ovaj cheatsheet teži da bude kratki pregled sintakse Scale. Licenca pripada Brendan O'Connor-u, pod CC-BY-SA 3.0 licencom.
language: ba
---
@@ -47,7 +47,7 @@ language: ba
| `var (x,y,z) = (1,2,3)` | destrukturirajuće vezivanje: otpakivanje torke podudaranjem uzoraka (pattern matching). |
| Loše`var x,y,z = (1,2,3)` | skrivena greška: svim varijablama dodijeljena cijela torka. |
| `var xs = List(1,2,3)` | lista (nepromjenjiva). |
-| `xs(2)` | indeksiranje zagradama ([slajdovi](http://www.slideshare.net/Odersky/fosdem-2009-1013261/27)). |
+| `xs(2)` | indeksiranje zagradama ([slajdovi](https://www.slideshare.net/Odersky/fosdem-2009-1013261/27)). |
| `1 :: List(2,3)` | cons. |
| `1 to 5` _isto kao_ `1 until 6` `1 to 10 by 2` | šećer za raspon (range). |
| `()` _(prazne zagrade)_ | jedina instanca Unit tipa (slično kao u C/Java void). |
@@ -56,11 +56,11 @@ language: ba
| `if (check) happy` _isto kao_ `if (check) happy else ()` | sintaksni šećer za uslov. |
| `while (x < 5) { println(x); x += 1}` | while petlja. |
| `do { println(x); x += 1} while (x < 5)` | do while petlja. |
-| `import scala.util.control.Breaks._` `breakable {` ` for (x <- xs) {` ` if (Math.random < 0.1) break` ` }` `}`| break ([slajdovi](http://www.slideshare.net/Odersky/fosdem-2009-1013261/21)). |
+| `import scala.util.control.Breaks._` `breakable {` ` for (x <- xs) {` ` if (Math.random < 0.1) break` ` }` `}`| break ([slajdovi](https://www.slideshare.net/Odersky/fosdem-2009-1013261/21)). |
| `for (x <- xs if x%2 == 0) yield x*10` _isto kao_ `xs.filter(_%2 == 0).map(_*10)` | for komprehensija: filter/map. |
| `for ((x,y) <- xs zip ys) yield x*y` _isto kao_ `(xs zip ys) map { case (x,y) => x*y }` | for komprehensija: destrukturirajuće vezivanje. |
| `for (x <- xs; y <- ys) yield x*y` _isto kao_ `xs flatMap {x => ys map {y => x*y}}` | for komprehensija: međuproizvod (vektorski proizvod). |
-| `for (x <- xs; y <- ys) {` `println("%d/%d = %.1f".format(x, y, x/y.toFloat))` `}` | for komprehensija: imperativ-asto. [sprintf-stil.](http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax) |
+| `for (x <- xs; y <- ys) {` `println("%d/%d = %.1f".format(x, y, x/y.toFloat))` `}` | for komprehensija: imperativ-asto. [sprintf-stil.](https://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax) |
| `for (i <- 1 to 5) {` `println(i)` `}` | for komprehensija: iteracija uključujući gornju granicu. |
| `for (i <- 1 until 5) {` `println(i)` `}` | for komprehensija: iteracija ne uključujući gornju granicu. |
| podudaranje uzoraka (pattern matching) | |
diff --git a/_ba/tour/abstract-types.md b/_ba/tour/abstract-type-members.md
similarity index 97%
rename from _ba/tour/abstract-types.md
rename to _ba/tour/abstract-type-members.md
index 10aa2d7d41..b7034b6922 100644
--- a/_ba/tour/abstract-types.md
+++ b/_ba/tour/abstract-type-members.md
@@ -2,9 +2,6 @@
layout: tour
title: Apstraktni tipovi
language: ba
-
-discourse: true
-
partof: scala-tour
num: 23
@@ -18,7 +15,7 @@ Trejtovi i apstraktne klase mogu imati apstraktne tipove kao članove.
To znači da konkretne implementacije definišu stvarni tip.
Slijedi primjer:
-```tut
+```scala mdoc
trait Buffer {
type T
val element: T
@@ -29,7 +26,7 @@ U gornjem primjeru smo definisali apstraktni tip `T`.
On se koristi za opis člana `element`.
Ovaj trejt možemo naslijediti u apstraktnoj klasi i dodati gornju granicu tipa za `T` da bi ga učinili preciznijim.
-```tut
+```scala mdoc
abstract class SeqBuffer extends Buffer {
type U
type T <: Seq[U]
@@ -43,7 +40,7 @@ mora biti podtip `Seq[U]` za neki novi apstraktni tip `U`.
Trejtovi ili [klase](classes.html) s apstraktnim tip-članovima se često koriste u kombinaciji s instanciranjem anonimnih klasa.
Radi ilustracije, pogledaćemo program koji radi s sekvencijalnim baferom koji sadrži listu integera:
-```tut
+```scala mdoc
abstract class IntSeqBuffer extends SeqBuffer {
type U = Int
}
@@ -64,7 +61,7 @@ Metoda `newIntSeqBuf` koristi anonimnu klasu kao implementaciju `IntSeqBuf` pos
Često je moguće pretvoriti apstraktni tip-član u tipski parametar klase i obrnuto.
Slijedi verzija gornjeg koda koji koristi tipske parametre:
-```tut
+```scala mdoc:nest
abstract class Buffer[+T] {
val element: T
}
diff --git a/_ba/tour/annotations.md b/_ba/tour/annotations.md
index 2040c97626..24b17a9012 100644
--- a/_ba/tour/annotations.md
+++ b/_ba/tour/annotations.md
@@ -2,13 +2,10 @@
layout: tour
title: Anotacije
language: ba
-
-discourse: true
-
partof: scala-tour
num: 32
-next-page: default-parameter-values
+next-page: packages-and-imports
previous-page: by-name-parameters
---
@@ -33,7 +30,7 @@ Redoslijed anotacijskih klauza nije bitan.
Određene anotacije će uzrokovati pad kompajliranja ako određeni uslovi nisu ispunjeni.
Npr, anotacija `@tailrec` osigurava da je metoda [tail-rekurzivna](https://en.wikipedia.org/wiki/Tail_call). Tail-rekurzija može zadržati memorijske zahtjeve konstantnim.
Evo kako se koristi na metodi koja izračunava faktorijel:
-```tut
+```scala mdoc
import scala.annotation.tailrec
def factorial(x: Int): Int = {
@@ -82,7 +79,7 @@ Java ima korisnički definisane metapodatke u formi [anotacija](https://docs.ora
I upotrijebiti je ovako:
```
-@Source(URL = "http://coders.com/",
+@Source(URL = "https://coders.com/",
mail = "support@coders.com")
public class MyClass extends HisClass ...
```
@@ -90,7 +87,7 @@ public class MyClass extends HisClass ...
Primjena anotacije u Scali izgleda kao poziv konstruktora, dok se za instanciranje Javinih anotacija moraju koristiti imenovani argumenti:
```
-@Source(URL = "http://coders.com/",
+@Source(URL = "https://coders.com/",
mail = "support@coders.com")
class MyScalaClass ...
```
@@ -108,14 +105,14 @@ ako se koristi naziv `value` onda se u Javi može koristiti i konstruktor-sintak
I upotrijebiti je kao:
```
-@SourceURL("http://coders.com/")
+@SourceURL("https://coders.com/")
public class MyClass extends HisClass ...
```
U ovom slučaju, Scala omogućuje istu sintaksu:
```
-@SourceURL("http://coders.com/")
+@SourceURL("https://coders.com/")
class MyScalaClass ...
```
@@ -123,7 +120,7 @@ Element `mail` je specificiran s podrazumijevanom vrijednošću tako da ne moram
Međutim, ako trebamo, ne možemo miješati dva Javina stila:
```
-@SourceURL(value = "http://coders.com/",
+@SourceURL(value = "https://coders.com/",
mail = "support@coders.com")
public class MyClass extends HisClass ...
```
@@ -131,7 +128,7 @@ public class MyClass extends HisClass ...
Scala omogućuje veću fleksibilnost u ovom pogledu:
```
-@SourceURL("http://coders.com/",
+@SourceURL("https://coders.com/",
mail = "support@coders.com")
class MyScalaClass ...
```
diff --git a/_ba/tour/automatic-closures.md b/_ba/tour/automatic-closures.md
deleted file mode 100644
index dc6e83de40..0000000000
--- a/_ba/tour/automatic-closures.md
+++ /dev/null
@@ -1,10 +0,0 @@
----
-layout: tour
-title: Automatic Type-Dependent Closure Construction
-
-discourse: false
-
-partof: scala-tour
-
-language: ba
----
diff --git a/_ba/tour/basics.md b/_ba/tour/basics.md
index ae47a88d38..97956e6149 100644
--- a/_ba/tour/basics.md
+++ b/_ba/tour/basics.md
@@ -2,9 +2,6 @@
layout: tour
title: Osnove
language: ba
-
-discourse: true
-
partof: scala-tour
num: 2
@@ -17,9 +14,9 @@ Na ovoj stranici ćemo objasniti osnove Scale.
## Probavanje Scale u browseru
-Scalu možete probati u Vašem browser sa ScalaFiddle aplikacijom.
+Scalu možete probati u Vašem browser sa Scastie aplikacijom.
-1. Idite na [https://scalafiddle.io](https://scalafiddle.io).
+1. Idite na [Scastie](https://scastie.scala-lang.org/).
2. Zalijepite `println("Hello, world!")` u lijevi panel.
3. Kliknite "Run" dugme. Izlaz će se pojaviti u desnom panelu.
@@ -33,7 +30,7 @@ Izrazi su izjave koje imaju vrijednost.
```
Rezultate izraza možete prikazati pomoću `println`.
-```tut
+```scala mdoc
println(1) // 1
println(1 + 1) // 2
println("Hello!") // Hello!
@@ -44,33 +41,33 @@ println("Hello," + " world!") // Hello, world!
Rezultatima možete dodijeliti naziv pomoću ključne riječi `val`.
-```tut
+```scala mdoc
val x = 1 + 1
println(x) // 2
```
-Imenovani rezultati, kao `x` ovdje, nazivaju se vrijednostima.
+Imenovani rezultati, kao `x` ovdje, nazivaju se vrijednostima.
Referenciranje vrijednosti ne okida njeno ponovno izračunavanje.
Vrijednosti se ne mogu mijenjati.
-```tut:fail
+```scala mdoc:fail
x = 3 // Ovo se ne kompajlira.
```
Tipovi vrijednosti mogu biti (automatski) zaključeni, ali možete i eksplicitno navesti tip:
-```tut
+```scala mdoc:nest
val x: Int = 1 + 1
```
-Primijetite da deklaracija tipa `Int` dolazi nakon identifikatora `x`. Također morate dodati i `:`.
+Primijetite da deklaracija tipa `Int` dolazi nakon identifikatora `x`. Također morate dodati i `:`.
### Varijable
Varijable su kao vrijednosti, osim što ih možete promijeniti. Varijable se definišu ključnom riječju `var`.
-```tut
+```scala mdoc:nest
var x = 1 + 1
x = 3 // Ovo se kompajlira jer je "x" deklarisano s "var" ključnom riječju.
println(x * x) // 9
@@ -78,7 +75,7 @@ println(x * x) // 9
Kao i s vrijednostima, tip možete eksplicitno navesti ako želite:
-```tut
+```scala mdoc:nest
var x: Int = 1 + 1
```
@@ -89,7 +86,7 @@ Izraze možete kombinovati okružujući ih s `{}`. Ovo se naziva blok.
Rezultat zadnjeg izraza u bloku je rezultat cijelog bloka, također.
-```tut
+```scala mdoc
println({
val x = 1 + 1
x + 1
@@ -102,7 +99,7 @@ Funkcije su izrazi koji primaju parametre.
Možete definisati anonimnu funkciju (bez imena) koja vraća cijeli broj plus jedan:
-```tut
+```scala mdoc
(x: Int) => x + 1
```
@@ -110,21 +107,21 @@ Na lijevoj strani `=>` je lista parametara. Na desnoj strani je izraz koji koris
Funkcije možete i imenovati.
-```tut
+```scala mdoc
val addOne = (x: Int) => x + 1
println(addOne(1)) // 2
```
Funkcije mogu imati više parametara.
-```tut
+```scala mdoc
val add = (x: Int, y: Int) => x + y
println(add(1, 2)) // 3
```
Ili bez parametara.
-```tut
+```scala mdoc
val getTheAnswer = () => 42
println(getTheAnswer()) // 42
```
@@ -135,7 +132,7 @@ Metode izgledaju i ponašaju se vrlo slično funkcijama, ali postoji nekoliko ra
Metode se definišu ključnom riječju `def`. Nakon `def` slijedi naziv, lista parametara, povratni tip, i tijelo.
-```tut
+```scala mdoc:nest
def add(x: Int, y: Int): Int = x + y
println(add(1, 2)) // 3
```
@@ -144,14 +141,14 @@ Primijetite da je povratni tip deklarisan _nakon_ liste parametara i dvotačke `
Metode mogu imati više listi parametara.
-```tut
+```scala mdoc
def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier
println(addThenMultiply(1, 2)(3)) // 9
```
Ili bez listi parametara ikako.
-```tut
+```scala mdoc
def name: String = System.getProperty("name")
println("Hello, " + name + "!")
```
@@ -159,32 +156,35 @@ println("Hello, " + name + "!")
Postoje i neke druge razlike, ali zasad, možete misliti o njima kao nečemu sličnom funkcijama.
Metode mogu imati višelinijske izraze također.
-```tut
+
+```scala mdoc
def getSquareString(input: Double): String = {
val square = input * input
square.toString
}
+println(getSquareString(2.5)) // 6.25
```
+
Zadnjo izraz u tijelu metode je povratna vrijednost metode. (Scala ima ključnu riječ `return`, ali se rijetko koristi.)
## Klase
Klasu možete definisati ključnom riječju `class` praćenom imenom i parametrima konstruktora.
-```tut
+```scala mdoc
class Greeter(prefix: String, suffix: String) {
def greet(name: String): Unit =
println(prefix + name + suffix)
}
```
-Povratni tip metode `greet` je `Unit`, koji kaže da metoda ne vraća ništa značajno.
-Koristi se slično kao `void` u Javi ili C-u.
-(Razlika je u tome što svaki Scalin izraz mora imati neku vrijednost, postoji singlton vrijednost tipa `Unit`, piše se `()`.
+Povratni tip metode `greet` je `Unit`, koji kaže da metoda ne vraća ništa značajno.
+Koristi se slično kao `void` u Javi ili C-u.
+(Razlika je u tome što svaki Scalin izraz mora imati neku vrijednost, postoji singlton vrijednost tipa `Unit`, piše se `()`.
Ne prenosi nikakvu korisnu informaciju.)
Instancu klase možete kreirati pomoću ključne riječi `new`.
-```tut
+```scala mdoc
val greeter = new Greeter("Hello, ", "!")
greeter.greet("Scala developer") // Hello, Scala developer!
```
@@ -193,16 +193,16 @@ Detaljniji pregled klasa biće dat [kasnije](classes.html).
## Case klase
-Scala ima poseban tip klase koji se zove "case" klasa.
+Scala ima poseban tip klase koji se zove "case" klasa.
Po defaultu, case klase su nepromjenjive i porede se po vrijednosti. Možete ih definisati s `case class` ključnim riječima.
-```tut
+```scala mdoc
case class Point(x: Int, y: Int)
```
Instancu case klase možete kreirati i bez ključne riječi `new`.
-```tut
+```scala mdoc
val point = Point(1, 2)
val anotherPoint = Point(1, 2)
val yetAnotherPoint = Point(2, 2)
@@ -210,17 +210,17 @@ val yetAnotherPoint = Point(2, 2)
I porede se po vrijednosti.
-```tut
+```scala mdoc
if (point == anotherPoint) {
- println(point + " and " + anotherPoint + " are the same.")
+ println(s"$point and $anotherPoint are the same.")
} else {
- println(point + " and " + anotherPoint + " are different.")
+ println(s"$point and $anotherPoint are different.")
} // Point(1,2) i Point(1,2) su iste.
if (point == yetAnotherPoint) {
- println(point + " and " + yetAnotherPoint + " are the same.")
+ println(s"$point and $yetAnotherPoint are the same.")
} else {
- println(point + " and " + yetAnotherPoint + " are different.")
+ println(s"$point and $yetAnotherPoint are different.")
} // Point(1,2) su Point(2,2) različite.
```
@@ -233,7 +233,7 @@ Objasnićemo ih u dubinu [kasnije](case-classes.html).
Objekti su jedine instance svojih definicija. Možete misliti o njima kao singltonima svoje vlastite klase.
Objekte možete definisati ključnom riječju `object`.
-```tut
+```scala mdoc
object IdFactory {
private var counter = 0
def create(): Int = {
@@ -245,7 +245,7 @@ object IdFactory {
Objektima možete pristupati referenciranjem njihovog imena.
-```tut
+```scala mdoc
val newId: Int = IdFactory.create()
println(newId) // 1
val newerId: Int = IdFactory.create()
@@ -260,7 +260,7 @@ Trejtovi su tipovi koji sadrže polja i metode. Više trejtova se može kombino
Definišu se pomoću `trait` ključne riječi.
-```tut
+```scala mdoc:nest
trait Greeter {
def greet(name: String): Unit
}
@@ -268,7 +268,7 @@ trait Greeter {
Metode trejtova mogu imati defaultnu implementaciju.
-```tut
+```scala mdoc:reset
trait Greeter {
def greet(name: String): Unit =
println("Hello, " + name + "!")
@@ -277,7 +277,7 @@ trait Greeter {
Možete naslijediti trejtove s `extends` ključnom riječi i redefinisati (override) implementacije s `override` ključnom riječi.
-```tut
+```scala mdoc
class DefaultGreeter extends Greeter
class CustomizableGreeter(prefix: String, postfix: String) extends Greeter {
@@ -299,12 +299,12 @@ Trejtove ćemo pokriti u dubinu [kasnije](traits.html).
## Glavna metoda
-Glavna metoda je ulazna tačka programa.
+Glavna metoda je ulazna tačka programa.
Java Virtuelna Mašina traži da se glavna metoda zove `main` i da prima jedan argument, niz stringova.
Koristeći objekt, možete definisati glavnu metodu ovako:
-```tut
+```scala mdoc
object Main {
def main(args: Array[String]): Unit =
println("Hello, Scala developer!")
diff --git a/_ba/tour/by-name-parameters.md b/_ba/tour/by-name-parameters.md
index 4a46335095..5cfc42f8cb 100644
--- a/_ba/tour/by-name-parameters.md
+++ b/_ba/tour/by-name-parameters.md
@@ -2,9 +2,6 @@
layout: tour
title: By-name parametri
language: ba
-
-discourse: true
-
partof: scala-tour
num: 31
@@ -16,7 +13,7 @@ previous-page: operators
_By-name parametri_ (u slobodnom prevodu "po-imenu parametri") se izračunavaju samo kada se koriste.
Oni su kontrastu sa _by-value parametrima_ ("po-vrijednosti parametri").
Da bi parametar bio pozivan by-name, dodajte `=>` prije njegovog tipa.
-```tut
+```scala mdoc
def calculate(input: => Int) = input * 37
```
By-name parametri imaju prednost da se ne izračunavaju ako se ne koriste u tijelu funkcije.
@@ -24,7 +21,7 @@ U drugu ruku, by-value parametri imaju prednost da se izračunavaju samo jednom.
Ovo je primjer kako bi mogli implementirati while petlju:
-```tut
+```scala mdoc
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
if (condition) {
body
diff --git a/_ba/tour/case-classes.md b/_ba/tour/case-classes.md
index 2f0babb99f..0c6de6d7b4 100644
--- a/_ba/tour/case-classes.md
+++ b/_ba/tour/case-classes.md
@@ -2,9 +2,6 @@
layout: tour
title: Case klase
language: ba
-
-discourse: true
-
partof: scala-tour
num: 11
@@ -20,7 +17,7 @@ U sljedećem koraku turneje, vidjećemo kako su korisne u [podudaranju uzoraka (
## Definisanje case klase
Minimalna case klasa se sastoji iz ključnih riječi `case class`, identifikatora, i liste parametara (koja može biti prazna):
-```tut
+```scala mdoc
case class Book(isbn: String)
val frankenstein = Book("978-0486282114")
diff --git a/_ba/tour/classes.md b/_ba/tour/classes.md
index aa5c36068c..29f170dca0 100644
--- a/_ba/tour/classes.md
+++ b/_ba/tour/classes.md
@@ -2,9 +2,6 @@
layout: tour
title: Klase
language: ba
-
-discourse: true
-
partof: scala-tour
num: 4
@@ -21,7 +18,7 @@ Tipovi, objekti i trejtovi biće pokriveni kasnije.
## Definisanje klase
Minimalna definicija klase sastoji se od riječi `class` i identifikatora. Imena klasa bi trebala počinjati velikim slovom.
-```tut
+```scala mdoc
class User
val user1 = new User
@@ -31,7 +28,7 @@ Ključna riječ `new` koristi se za kreiranje instance klase.
Međutim, često ćete imati konstruktor i tijelo klase.
Slijedi definicija klase `Point` (en. tačka):
-```tut
+```scala mdoc
class Point(var x: Int, var y: Int) {
def move(dx: Int, dy: Int): Unit = {
@@ -59,7 +56,7 @@ Pošto `toString` prebrisava metodu `toString` iz [`AnyRef`](unified-types.html)
Konstruktori mogu imati opcione parametre koristeći podrazumijevane vrijednosti:
-```tut
+```scala mdoc:nest
class Point(var x: Int = 0, var y: Int = 0)
val origin = new Point // x and y are both set to 0
@@ -70,7 +67,7 @@ println(point1.x) // prints 1
U ovoj verziji klase `Point`, `x` i `y` imaju podrazumijevanu vrijednost `0` tako da ne morate proslijediti argumente.
Međutim, pošto se argumenti konstruktora čitaju s lijeva na desno, ako želite proslijediti samo `y` vrijednost, morate imenovati parametar.
-```
+```scala mdoc:nest
class Point(var x: Int = 0, var y: Int = 0)
val point2 = new Point(y=2)
println(point2.y) // prints 2
@@ -81,7 +78,7 @@ Ovo je također dobra praksa zbog poboljšanja čitljivosti.
## Privatni članovi i sintaksa getera/setera
Članovi su javni (`public`) po defaultu.
Koristite `private` modifikator pristupa da sakrijete članove klase.
-```tut
+```scala mdoc:nest
class Point {
private var _x = 0
private var _y = 0
@@ -111,14 +108,14 @@ Primijetite specijalnu sintaksu za setere: metoda ima `_=` nadodano na identifik
Parametri primarnog konstruktora s `val` i `var` su javni.
Međutim, pošto su `val` nepromjenjivi, ne možete napisati sljedeće.
-```
+```scala mdoc:fail
class Point(val x: Int, val y: Int)
val point = new Point(1, 2)
point.x = 3 // <-- does not compile
```
Parametri bez `val` ili `var` su privatne vrijednosti, vidljive samo unutar klase.
-```
+```scala mdoc:fail
class Point(x: Int, y: Int)
val point = new Point(1, 2)
point.x // <-- does not compile
diff --git a/_ba/tour/compound-types.md b/_ba/tour/compound-types.md
index 8f84b72176..3781e866e3 100644
--- a/_ba/tour/compound-types.md
+++ b/_ba/tour/compound-types.md
@@ -2,14 +2,11 @@
layout: tour
title: Složeni tipovi
language: ba
-
-discourse: true
-
partof: scala-tour
num: 24
next-page: self-types
-previous-page: abstract-types
+previous-page: abstract-type-members
---
@@ -18,7 +15,7 @@ U Scali ovo može biti izraženo pomoću *složenih tipova*, koji su presjeci ti
Pretpostavimo da imamo dva trejta: `Cloneable` i `Resetable`:
-```tut
+```scala mdoc
trait Cloneable extends java.lang.Cloneable {
override def clone(): Cloneable = {
super.clone().asInstanceOf[Cloneable]
@@ -56,4 +53,4 @@ def cloneAndReset(obj: Cloneable with Resetable): Cloneable = {
Složeni tipovi mogu se sastojati od više tipova i mogu imati jednu rafinaciju koja može biti korištena da suzi potpis postojećih članova objekta.
General forma je: `A with B with C ... { refinement }`
-Primjer za upotrebu rafinacije dat je na stranici o [apstraktnim tipovima](abstract-types.html).
+Primjer za upotrebu rafinacije dat je na stranici o [apstraktnim tipovima](abstract-type-members.html).
diff --git a/_ba/tour/default-parameter-values.md b/_ba/tour/default-parameter-values.md
index 2071d3a661..f4fc257900 100644
--- a/_ba/tour/default-parameter-values.md
+++ b/_ba/tour/default-parameter-values.md
@@ -2,9 +2,6 @@
layout: tour
title: Podrazumijevane vrijednosti parametara
language: ba
-
-discourse: true
-
partof: scala-tour
num: 33
@@ -16,7 +13,7 @@ prerequisite-knowledge: named-arguments, function syntax
Scala omogućuje davanje podrazumijevanih vrijednosti parametrima koje dozvoljavaju korisniku metode da izostavi te parametre.
-```tut
+```scala mdoc
def log(message: String, level: String = "INFO") = println(s"$level: $message")
log("System starting") // prints INFO: System starting
@@ -25,7 +22,7 @@ log("User not found", "WARNING") // prints WARNING: User not found
Parametar `level` ima podrazumijevanu vrijednost tako da je opcioni. Na zadnjoj liniji, argument `"WARNING"` prebrisava podrazumijevani argument `"INFO"`. Gdje biste koristili overloadane metode u Javi, možete koristiti metode s opcionim parametrima da biste postigli isti efekat. Međutim, ako korisnik izostavi argument, bilo koji sljedeći argumenti moraju biti imenovani.
-```tut
+```scala mdoc
class Point(val x: Double = 0, val y: Double = 0)
val point1 = new Point(y = 1)
@@ -34,7 +31,7 @@ Ovdje moramo reći `y = 1`.
Podrazumijevani parametri u Scali nisu opcioni kada se koriste iz Java koda:
-```tut
+```scala mdoc:reset
// Point.scala
class Point(val x: Double = 0, val y: Double = 0)
```
diff --git a/_ba/tour/extractor-objects.md b/_ba/tour/extractor-objects.md
index 7aef9bd432..0d0618aa00 100644
--- a/_ba/tour/extractor-objects.md
+++ b/_ba/tour/extractor-objects.md
@@ -2,9 +2,6 @@
layout: tour
title: Ekstraktor objekti
language: ba
-
-discourse: true
-
partof: scala-tour
num: 16
@@ -14,15 +11,15 @@ previous-page: regular-expression-patterns
---
Ekstraktor objekat je objekat koji ima `unapply` metodu.
-Dok je `apply` metoda kao konstruktor koji uzima argumente i kreira objekat, `unapply` metoda prima objekat i pokušava vratiti argumente.
+Dok je `apply` metoda kao konstruktor koji uzima argumente i kreira objekat, `unapply` metoda prima objekat i pokušava vratiti argumente.
Ovo se najčešće koristi u podudaranju uzoraka i parcijalnim funkcijama.
-```tut
+```scala mdoc
import scala.util.Random
object CustomerID {
- def apply(name: String) = s"$name--${Random.nextLong}"
+ def apply(name: String) = s"$name--${Random.nextLong()}"
def unapply(customerID: String): Option[String] = {
val name = customerID.split("--").head
@@ -37,14 +34,14 @@ customer1ID match {
}
```
-Metoda `apply` kreira `CustomerID` string od argumenta `name`.
-Metoda `unapply` radi suprotno da dobije `name` nazad.
-Kada pozovemo `CustomerID("Sukyoung")`, to je skraćena sintaksa za `CustomerID.apply("Sukyoung")`.
+Metoda `apply` kreira `CustomerID` string od argumenta `name`.
+Metoda `unapply` radi suprotno da dobije `name` nazad.
+Kada pozovemo `CustomerID("Sukyoung")`, to je skraćena sintaksa za `CustomerID.apply("Sukyoung")`.
Kada pozovemo `case CustomerID(name) => customer1ID`, ustvari pozivamo `unapply` metodu.
Metoda `unapply` se može koristiti i za dodjelu vrijednosti.
-```tut
+```scala mdoc
val customer2ID = CustomerID("Nico")
val CustomerID(name) = customer2ID
println(name) // prints Nico
@@ -52,7 +49,7 @@ println(name) // prints Nico
Ovo je ekvivalentno `val name = CustomerID.unapply(customer2ID).get`. Ako se uzorak ne podudari, baciće se `scala.MatchError` izuzetak:
-```tut:fail
+```scala mdoc:crash
val CustomerID(name2) = "--asdfasdfasdf"
```
diff --git a/_ba/tour/for-comprehensions.md b/_ba/tour/for-comprehensions.md
index efdeb57dc8..7d5d0f9166 100644
--- a/_ba/tour/for-comprehensions.md
+++ b/_ba/tour/for-comprehensions.md
@@ -21,7 +21,7 @@ Komprehensija evaluira tijelo `e` za svako vezivanje varijable generisano od str
Slijedi primjer:
-```tut
+```scala mdoc
case class User(name: String, age: Int)
val userBase = List(User("Travis", 28),
@@ -38,7 +38,7 @@ twentySomethings.foreach(name => println(name)) // prints Travis Dennis
Slijedi malo komplikovaniji primjer koji s dva generatora. Izračunava sve parove brojeva između `0` i `n-1` čija je suma jednaka vrijednosti `v`:
-```tut
+```scala mdoc
def foo(n: Int, v: Int) =
for (i <- 0 until n;
j <- i until n if i + j == v)
@@ -54,5 +54,5 @@ Ovdje je `n == 10` i `v == 10`. U prvoj iteraciji, `i == 0` i `j == 0` tako da `
Bez `if` čuvara, ovo bi ispisalo sljedeće:
```
-(0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (0, 7) (0, 8) (0, 9) (1, 1) ...
+(0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (0, 7) (0, 8) (0, 9) (1, 0) ...
```
diff --git a/_ba/tour/generic-classes.md b/_ba/tour/generic-classes.md
index b9601f024c..6b52e9ccd8 100644
--- a/_ba/tour/generic-classes.md
+++ b/_ba/tour/generic-classes.md
@@ -2,9 +2,6 @@
layout: tour
title: Generičke klase
language: ba
-
-discourse: true
-
partof: scala-tour
num: 18
@@ -22,10 +19,11 @@ Vrlo su korisne za implementiranje kolekcija.
Generičke klase primaju tip kao parametar u uglastim zagradama `[]`.
Konvencija je da se koristi slovo `A` kao identifikator tipa, mada se može koristiti bilo koje ime.
-```tut
+```scala mdoc
class Stack[A] {
private var elements: List[A] = Nil
- def push(x: A) { elements = x :: elements }
+ def push(x: A): Unit =
+ elements = x :: elements
def peek: A = elements.head
def pop(): A = {
val currentTop = peek
diff --git a/_ba/tour/higher-order-functions.md b/_ba/tour/higher-order-functions.md
index 50531716b0..56f1c1807a 100644
--- a/_ba/tour/higher-order-functions.md
+++ b/_ba/tour/higher-order-functions.md
@@ -2,9 +2,6 @@
layout: tour
title: Funkcije višeg reda
language: ba
-
-discourse: true
-
partof: scala-tour
num: 8
@@ -17,15 +14,15 @@ Scala dozvoljava definisanje funkcija višeg reda.
To su funkcije koje _primaju druge funkcije kao parametre_, ili čiji je _rezultat funkcija_.
Ovo je funkcija `apply` koja uzima drugu funkciju `f` i vrijednost `v` i primjenjuje funkciju `f` na `v`:
-```tut
+```scala mdoc
def apply(f: Int => String, v: Int) = f(v)
```
_Napomena: metode se automatski pretvaraju u funkcije ako to kontekst zahtijeva._
Ovo je još jedan primjer:
-
-```tut
+
+```scala mdoc
class Decorator(left: String, right: String) {
def layout[A](x: A) = left + x.toString() + right
}
@@ -36,7 +33,7 @@ object FunTest extends App {
println(apply(decorator.layout, 7))
}
```
-
+
Izvršavanjem se dobije izlaz:
```
diff --git a/_ba/tour/implicit-conversions.md b/_ba/tour/implicit-conversions.md
index 69609f61f9..5a1ea3b9fa 100644
--- a/_ba/tour/implicit-conversions.md
+++ b/_ba/tour/implicit-conversions.md
@@ -2,9 +2,6 @@
layout: tour
title: Implicitne konverzije
language: ba
-
-discourse: true
-
partof: scala-tour
num: 27
@@ -46,11 +43,11 @@ Implicitno importovani objekt `scala.Predef` deklariše nekoliko predefinisanih
Naprimjer, kada se pozivaju Javine metode koje očekuju `java.lang.Integer`, možete proslijediti `scala.Int`.
Možete, zato što `Predef` uključuje slj. implicitnu konverziju:
-```tut
+```scala mdoc
import scala.language.implicitConversions
-implicit def int2Integer(x: Int) =
- java.lang.Integer.valueOf(x)
+implicit def int2Integer(x: Int): Integer =
+ Integer.valueOf(x)
```
Pošto su implicitne konverzije opasne ako se koriste pogrešno, kompajler upozorava kada kompajlira definiciju implicitne konverzije.
diff --git a/_ba/tour/implicit-parameters.md b/_ba/tour/implicit-parameters.md
index d3ebff2667..c39d87d626 100644
--- a/_ba/tour/implicit-parameters.md
+++ b/_ba/tour/implicit-parameters.md
@@ -2,9 +2,6 @@
layout: tour
title: Implicitni parametri
language: ba
-
-discourse: true
-
partof: scala-tour
num: 26
@@ -25,7 +22,7 @@ Argumenti koji se mogu proslijediti kao implicitni parametri spadaju u dvije kat
U sljedećem primjeru definisaćemo metodu `sum` koja izračunava sumu liste elemenata koristeći `add` i `unit` operacije monoida.
Molimo primijetite da implicitne vrijednosti ne mogu biti top-level, već moraju biti članovi templejta.
-```tut
+```scala mdoc
abstract class SemiGroup[A] {
def add(x: A, y: A): A
}
diff --git a/_ba/tour/inner-classes.md b/_ba/tour/inner-classes.md
index 0917237fe7..ef72aa8929 100644
--- a/_ba/tour/inner-classes.md
+++ b/_ba/tour/inner-classes.md
@@ -2,13 +2,10 @@
layout: tour
title: Unutarnje klase
language: ba
-
-discourse: true
-
partof: scala-tour
num: 22
-next-page: abstract-types
+next-page: abstract-type-members
previous-page: lower-type-bounds
---
@@ -20,12 +17,12 @@ Pretpostavimo da želimo da nas kompejler spriječi da pomiješamo koji čvorovi
Radi ilustracije razlike, prikazaćemo implementaciju klase grafa:
-```tut
+```scala mdoc
class Graph {
class Node {
var connectedNodes: List[Node] = Nil
- def connectTo(node: Node) {
- if (connectedNodes.find(node.equals).isEmpty) {
+ def connectTo(node: Node): Unit = {
+ if (!connectedNodes.exists(node.equals)) {
connectedNodes = node :: connectedNodes
}
}
@@ -38,11 +35,11 @@ class Graph {
}
}
```
-
+
U našem programu, grafovi su predstavljeni listom čvorova (`List[Node]`).
Svaki čvor ima listu drugih čvorova s kojima je povezan (`connectedNodes`). Klasa `Node` je _path-dependent tip_ jer je ugniježdena u klasi `Graph`. Stoga, svi čvorovi u `connectedNodes` moraju biti kreirani koristeći `newNode` iz iste instance klase `Graph`.
-```tut
+```scala mdoc
val graph1: Graph = new Graph
val node1: graph1.Node = graph1.newNode
val node2: graph1.Node = graph1.newNode
@@ -50,14 +47,14 @@ val node3: graph1.Node = graph1.newNode
node1.connectTo(node2)
node3.connectTo(node1)
```
-
+
Eksplicitno smo deklarisali tip `node1`, `node2`, i `node3` kao `graph1.Node` zbog jasnosti ali ga je kompajler mogao sam zaključiti. Pošto kada pozivamo `graph1.newNode` koja poziva `new Node`, metoda koristi instancu `Node` specifičnu instanci `graph1`.
Da imamo dva grafa, sistem tipova Scale ne dozvoljava miješanje čvorova definisanih u različitim grafovima,
jer čvorovi različitih grafova imaju različit tip.
Ovo je primjer netačnog programa:
-
-```
+
+```scala mdoc:fail
val graph1: Graph = new Graph
val node1: graph1.Node = graph1.newNode
val node2: graph1.Node = graph1.newNode
@@ -72,13 +69,13 @@ U Javi bi zadnja linija prethodnog primjera bila tačna.
Za čvorove oba grafa, Java bi dodijelila isti tip `Graph.Node`; npr. `Node` bi imala prefiks klase `Graph`.
U Scali takav tip je također moguće izraziti, piše se kao `Graph#Node`.
Ako želimo povezati čvorove različitih grafova, moramo promijeniti definiciju naše inicijalne implementacije grafa:
-
-```tut
+
+```scala mdoc:nest
class Graph {
class Node {
var connectedNodes: List[Graph#Node] = Nil
- def connectTo(node: Graph#Node) {
- if (connectedNodes.find(node.equals).isEmpty) {
+ def connectTo(node: Graph#Node): Unit = {
+ if (!connectedNodes.exists(node.equals)) {
connectedNodes = node :: connectedNodes
}
}
@@ -91,6 +88,6 @@ class Graph {
}
}
```
-
+
> Primijetite da ovaj program ne dozvoljava da dodamo čvor u dva različita grafa.
Ako bi htjeli ukloniti i ovo ograničenje, moramo promijeniti tipski parametar `nodes` u `Graph#Node`.
diff --git a/_ba/tour/lower-type-bounds.md b/_ba/tour/lower-type-bounds.md
index cf310ead80..85dd54a401 100644
--- a/_ba/tour/lower-type-bounds.md
+++ b/_ba/tour/lower-type-bounds.md
@@ -2,9 +2,6 @@
layout: tour
title: Donja granica tipa
language: ba
-
-discourse: true
-
partof: scala-tour
num: 21
@@ -20,7 +17,7 @@ Izraz `B >: A` izražava tipski parametar `B` ili apstraktni tip `B` koji je nad
Kroz sljedeći primjer vidjećemo zašto je ovo korisno:
-```tut:fail
+```scala mdoc:fail
trait Node[+B] {
def prepend(elem: B): Node[B]
}
@@ -46,7 +43,7 @@ Ovo ne radi jer su funkcije *kontra*varijantne u svojim tipovima parametara i *k
Da bismo popravili ovo, moramo zamijeniti varijansu tipskog parametra `elem` u `prepend`.
Ovo radimo uvođenjem novog tipskog parametra `U` koji ima `B` kao svoju donju granicu tipa.
-```tut
+```scala mdoc
trait Node[+B] {
def prepend[U >: B](elem: U): Node[U]
}
@@ -63,7 +60,7 @@ case class Nil[+B]() extends Node[B] {
```
Sada možemo uraditi sljedeće:
-```tut
+```scala mdoc
trait Bird
case class AfricanSwallow() extends Bird
case class EuropeanSwallow() extends Bird
@@ -71,6 +68,6 @@ case class EuropeanSwallow() extends Bird
val africanSwallowList= ListNode[AfricanSwallow](AfricanSwallow(), Nil())
val birdList: Node[Bird] = africanSwallowList
-birdList.prepend(new EuropeanSwallow)
+birdList.prepend(EuropeanSwallow())
```
`Node[Bird]` može biti dodijeljena `africanSwallowList` ali onda prihvatiti `EuropeanSwallow`e.
diff --git a/_ba/tour/mixin-class-composition.md b/_ba/tour/mixin-class-composition.md
index 7a1940bcc0..a8216abfb6 100644
--- a/_ba/tour/mixin-class-composition.md
+++ b/_ba/tour/mixin-class-composition.md
@@ -2,21 +2,18 @@
layout: tour
title: Kompozicija mixin klasa
language: ba
-
-discourse: true
-
partof: scala-tour
num: 6
next-page: higher-order-functions
-previous-page: traits
+previous-page: tuples
prerequisite-knowledge: inheritance, traits, abstract-classes, unified-types
---
Mixini su trejtovi koji se koriste za kompoziciju klase.
-```tut
+```scala mdoc
abstract class A {
val message: String
}
@@ -32,23 +29,23 @@ val d = new D
d.message // I'm an instance of class B
d.loudMessage // I'M AN INSTANCE OF CLASS B
```
-Klasa `D` je nadklasa od `B` i mixina `C`.
+Klasa `D` je nadklasa od `B` i mixina `C`.
Klase mogu imati samo jednu nadklasu alid mogu imati više mixina (koristeći ključne riječi `extends` i `with` respektivno). Mixini i nadklasa mogu imati isti nadtip.
Pogledajmo sada zanimljiviji primjer počevši od apstraktne klase:
-
-```tut
+
+```scala mdoc
abstract class AbsIterator {
type T
def hasNext: Boolean
def next(): T
}
```
-
+
Klasa ima apstraktni tip `T` i standardne metode iteratora.
Dalje, implementiraćemo konkretnu klasu (svi apstraktni članovi `T`, `hasNext`, i `next` imaju implementacije):
-```tut
+```scala mdoc
class StringIterator(s: String) extends AbsIterator {
type T = Char
private var i = 0
@@ -62,14 +59,14 @@ class StringIterator(s: String) extends AbsIterator {
```
`StringIterator` prima `String` i može se koristiti za iteraciju nad `String`om (npr. da vidimo da li sadrži određeni karakter).
-
+
trait RichIterator extends AbsIterator {
- def foreach(f: T => Unit) { while (hasNext) f(next()) }
+ def foreach(f: T => Unit): Unit = { while (hasNext) f(next()) }
}
Kreirajmo sada trejt koji također nasljeđuje `AbsIterator`.
-```tut
+```scala mdoc
trait RichIterator extends AbsIterator {
def foreach(f: T => Unit): Unit = while (hasNext) f(next())
}
@@ -77,16 +74,16 @@ trait RichIterator extends AbsIterator {
Pošto je `RichIterator` trejt, on ne mora implementirati apstraktne članove `AbsIterator`a.
-Željeli bismo iskombinirati funkcionalnosti `StringIterator`a i `RichIterator`a u jednoj klasi.
+Željeli bismo iskombinirati funkcionalnosti `StringIterator`a i `RichIterator`a u jednoj klasi.
-```tut
+```scala mdoc
object StringIteratorTest extends App {
class Iter extends StringIterator("Scala") with RichIterator
val iter = new Iter
iter foreach println
}
```
-
+
Nova klasa `Iter` ima `StringIterator` kao nadklasu i `RichIterator` kao mixin.
S jednostrukim nasljeđivanjem ne bismo mogli postići ovaj nivo fleksibilnosti.
diff --git a/_ba/tour/multiple-parameter-lists.md b/_ba/tour/multiple-parameter-lists.md
index ba0042557c..68230aa12b 100644
--- a/_ba/tour/multiple-parameter-lists.md
+++ b/_ba/tour/multiple-parameter-lists.md
@@ -2,9 +2,6 @@
layout: tour
title: Curry-jevanje
language: ba
-
-discourse: true
-
partof: scala-tour
num: 10
@@ -19,7 +16,7 @@ onda će to vratiti funkciju koja prima preostale liste parametara kao argumente
Primjer:
-```tut
+```scala mdoc
object CurryTest extends App {
def filter(xs: List[Int], p: Int => Boolean): List[Int] =
diff --git a/_ba/tour/named-arguments.md b/_ba/tour/named-arguments.md
index a2e98b1d56..6656b02da2 100644
--- a/_ba/tour/named-arguments.md
+++ b/_ba/tour/named-arguments.md
@@ -2,9 +2,6 @@
layout: tour
title: Imenovani parametri
language: ba
-
-discourse: true
-
partof: scala-tour
num: 34
@@ -15,7 +12,7 @@ prerequisite-knowledge: function-syntax
Kada se pozivaju metode, možete koristiti imena varijabli eksplicitno pri pozivu:
-```tut
+```scala mdoc
def printName(first: String, last: String): Unit = {
println(first + " " + last)
}
diff --git a/_ba/tour/nested-functions.md b/_ba/tour/nested-functions.md
index f7122a33f8..1a00eaba59 100644
--- a/_ba/tour/nested-functions.md
+++ b/_ba/tour/nested-functions.md
@@ -2,9 +2,6 @@
layout: tour
title: Ugniježdene metode
language: ba
-
-discourse: true
-
partof: scala-tour
num: 9
@@ -16,7 +13,7 @@ previous-page: higher-order-functions
U Scali je moguće ugnježdavati definicije metode.
Sljedeći objekt sadrži metodu `factorial` za računanje faktorijela datog broja:
-```tut
+```scala mdoc
def factorial(x: Int): Int = {
def fact(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
diff --git a/_ba/tour/operators.md b/_ba/tour/operators.md
index 363cf74858..f1e8f3da07 100644
--- a/_ba/tour/operators.md
+++ b/_ba/tour/operators.md
@@ -2,9 +2,6 @@
layout: tour
title: Operatori
language: ba
-
-discourse: true
-
partof: scala-tour
num: 30
@@ -28,9 +25,9 @@ Međutim, lakše je čitati kada se napiše kao infiksni operator:
## Definisanje i korištenje operatora
Možete koristiti bilo koji legalni identifikator kao operator.
To uključuje i imena kao `add` ili simbole kao `+`.
-```tut
-case class Vec(val x: Double, val y: Double) {
- def +(that: Vec) = new Vec(this.x + that.x, this.y + that.y)
+```scala mdoc
+case class Vec(x: Double, y: Double) {
+ def +(that: Vec) = Vec(this.x + that.x, this.y + that.y)
}
val vector1 = Vec(1.0, 1.0)
@@ -45,7 +42,7 @@ Koristeći zagrade, možete pisati kompleksne izraze s čitljivom sintaksom.
Slijedi definicija klase `MyBool` koja definiše tri metode `and`, `or`, i `negate`.
-```tut
+```scala mdoc
case class MyBool(x: Boolean) {
def and(that: MyBool): MyBool = if (x) that else this
def or(that: MyBool): MyBool = if (x) this else that
@@ -55,7 +52,7 @@ case class MyBool(x: Boolean) {
Sada je moguće koristiti `and` i `or` kao infiksne operatore:
-```tut
+```scala mdoc
def not(x: MyBool) = x.negate
def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
```
@@ -74,7 +71,7 @@ Kada izraz koristi više operatora, operatori se primjenjuju bazirano na priorit
&
^
|
-(sva slova)
+(sva slova, $, _)
```
Ovo se odnosi na metode koje definišete. Npr, sljedeći izraz:
```
diff --git a/_ba/tour/package-objects.md b/_ba/tour/package-objects.md
new file mode 100644
index 0000000000..cef657c1f5
--- /dev/null
+++ b/_ba/tour/package-objects.md
@@ -0,0 +1,14 @@
+---
+layout: tour
+title: Package Objects
+language: ba
+partof: scala-tour
+
+num: 36
+previous-page: packages-and-imports
+---
+
+# Package objects
+
+(this section of the tour has not been translated yet. pull request
+with translation welcome!)
diff --git a/_ba/tour/packages-and-imports.md b/_ba/tour/packages-and-imports.md
index b466c5946a..b21770e3d0 100644
--- a/_ba/tour/packages-and-imports.md
+++ b/_ba/tour/packages-and-imports.md
@@ -2,14 +2,11 @@
layout: tour
title: Packages and Imports
language: ba
-
-discourse: true
-
partof: scala-tour
num: 35
previous-page: named-arguments
-next-page: type-inference
+next-page: package-objects
---
# Packages and Imports
diff --git a/_ba/tour/pattern-matching.md b/_ba/tour/pattern-matching.md
index 9e304a3fd0..e303e05d63 100644
--- a/_ba/tour/pattern-matching.md
+++ b/_ba/tour/pattern-matching.md
@@ -2,9 +2,6 @@
layout: tour
title: Podudaranje uzoraka (pattern matching)
language: ba
-
-discourse: true
-
partof: scala-tour
num: 12
@@ -19,7 +16,7 @@ Podudaranje uzoraka je mehanizam za provjeranje da li vrijednost odgovara uzroku
## Sintaksa
Izraz za podudaranje ima vrijednost, `match` ključnu riječ, i bar jednu `case` klauzu.
-```tut
+```scala mdoc
import scala.util.Random
val x: Int = Random.nextInt(10)
@@ -37,7 +34,7 @@ Zadnji slučaj, `_`, je "uhvati sve" slučaj za brojeve veće od 2.
Slučajevi se još zovu i _alternative_.
Izrazi za podudaranje imaju vrijednost.
-```tut
+```scala mdoc
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
@@ -53,7 +50,7 @@ Stoga, metoda `matchTest` vraća `String`.
Case klase su posebno korisne za podudaranje uzoraka.
-```tut
+```scala mdoc
abstract class Notification
case class Email(sender: String, title: String, body: String) extends Notification
@@ -121,9 +118,9 @@ U `case Email(email, _, _) if importantPeopleInfo.contains(email)`, uzorak se po
## Podudaranje samo tipa
Možete podudarati samo tip ovako:
-```tut
+```scala mdoc
abstract class Device
-case class Phone(model: String) extends Device{
+case class Phone(model: String) extends Device {
def screenOff = "Turning screen off"
}
case class Computer(model: String) extends Device {
@@ -143,7 +140,7 @@ Konvencija je da se koristi prvo slovo tipa kao identifikator (`p` i `c` ovdje).
Trejtovi i klase mogu biti `sealed` što znači da svi podtipovi moraju biti reklarisani u istom fajlu.
Ovo osigurava da su svi podtipovi poznati.
-```tut
+```scala mdoc
sealed abstract class Furniture
case class Couch() extends Furniture
case class Chair() extends Furniture
diff --git a/_ba/tour/polymorphic-methods.md b/_ba/tour/polymorphic-methods.md
index 250cd850ee..a5ad6e27f4 100644
--- a/_ba/tour/polymorphic-methods.md
+++ b/_ba/tour/polymorphic-methods.md
@@ -2,9 +2,6 @@
layout: tour
title: Polimorfne metode
language: ba
-
-discourse: true
-
partof: scala-tour
num: 28
@@ -21,7 +18,7 @@ Vrijednosni parameteri ("obični") su ograđeni parom zagrada, dok su tipski par
Slijedi primjer:
-```tut
+```scala mdoc
def listOfDuplicates[A](x: A, length: Int): List[A] = {
if (length < 1)
Nil
diff --git a/_ba/tour/regular-expression-patterns.md b/_ba/tour/regular-expression-patterns.md
index bf6a256e76..558b039a24 100644
--- a/_ba/tour/regular-expression-patterns.md
+++ b/_ba/tour/regular-expression-patterns.md
@@ -2,9 +2,6 @@
layout: tour
title: Regularni izrazi
language: ba
-
-discourse: true
-
partof: scala-tour
num: 15
@@ -17,7 +14,7 @@ previous-page: singleton-objects
Regularni izrazi su stringovi koji se mogu koristiti za traženje uzoraka u podacima.
Bilo koji string se može pretvoriti u regularni izraz pozivom `.r` metode.
-```tut
+```scala mdoc
import scala.util.matching.Regex
val numberPattern: Regex = "[0-9]".r
@@ -33,7 +30,7 @@ U gornjem primjeru, `numberPattern` je `Regex`
Također, možete tražiti grupe regularnih izraza koristeći zagrade.
-```tut
+```scala mdoc
import scala.util.matching.Regex
val keyValPattern: Regex = "([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)".r
diff --git a/_ba/tour/self-types.md b/_ba/tour/self-types.md
index 0160d48250..9b0ccd95a2 100644
--- a/_ba/tour/self-types.md
+++ b/_ba/tour/self-types.md
@@ -2,9 +2,6 @@
layout: tour
title: Self-tipovi
language: ba
-
-discourse: true
-
partof: scala-tour
num: 25
@@ -20,7 +17,7 @@ Self-tip je način da se suzi tip `this` ili drugi identifikator koji je alijas
Sintaksa izgleda kao obična funkcija ali znači nešto sasvim drugačije.
Da bi koristili self-tip u trejtu, napišite identifikator, tip drugog trejta za umiksavanje, i `=>` (tj. `someIdentifier: SomeOtherTrait =>`).
-```tut
+```scala mdoc
trait User {
def username: String
}
diff --git a/_ba/tour/singleton-objects.md b/_ba/tour/singleton-objects.md
index 0b570b4593..7f8ac84ba4 100644
--- a/_ba/tour/singleton-objects.md
+++ b/_ba/tour/singleton-objects.md
@@ -2,9 +2,6 @@
layout: tour
title: Singlton objekti
language: ba
-
-discourse: true
-
partof: scala-tour
num: 13
@@ -34,7 +31,7 @@ Kao i `val`, singlton objekti mogu biti definisani kao članovi [trejta](traits.
Singlton objekt može naslijediti klase i trejtove.
Ustvari, [case klasa](case-classes.html) bez [tipskih parametara](generic-classes.html)
će podrazumijevano kreirati singlton objekt s istim imenom,
-i implementiranim [`Function*`](http://www.scala-lang.org/api/current/scala/Function1.html) trejtom.
+i implementiranim [`Function*`](https://www.scala-lang.org/api/current/scala/Function1.html) trejtom.
## Kompanjoni (prijatelji) ##
@@ -47,7 +44,7 @@ ako krug s velikim “C” ili “O” ima savijenu ivicu (kao papir), možete k
Klasa i njen kompanjon objekt, ako ga ima, moraju biti definisani u istom izvornom fajlu:
-```tut
+```scala mdoc
class IntPair(val x: Int, val y: Int)
object IntPair {
diff --git a/_ba/tour/tour-of-scala.md b/_ba/tour/tour-of-scala.md
index e30b2cc5c5..9ebb53983b 100644
--- a/_ba/tour/tour-of-scala.md
+++ b/_ba/tour/tour-of-scala.md
@@ -2,9 +2,6 @@
layout: tour
title: Uvod
language: ba
-
-discourse: true
-
partof: scala-tour
num: 1
@@ -45,7 +42,7 @@ Konkretno, sistem tipova podržava sljedeće:
* [generičke klase](generic-classes.html)
* [anotacije varijanse](variances.html)
* [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
+* [unutarnje klase](inner-classes.html) i [apstraktne tipove](abstract-type-members.html) kao članove objekta
* [složene tipove](compound-types.html)
* [eksplicitno tipizirane samo-reference](self-types.html)
* implicitne [parametre](implicit-parameters.html) i [konverzije](implicit-conversions.html)
diff --git a/_ba/tour/traits.md b/_ba/tour/traits.md
index d4ac8596e0..8f7a82cc9e 100644
--- a/_ba/tour/traits.md
+++ b/_ba/tour/traits.md
@@ -2,13 +2,10 @@
layout: tour
title: Trejtovi
language: ba
-
-discourse: true
-
partof: scala-tour
num: 5
-next-page: mixin-class-composition
+next-page: tuples
previous-page: classes
assumed-knowledge: expressions, classes, generics, objects, companion-objects
@@ -21,12 +18,12 @@ Klase i objekti mogu naslijediti trejtove ali trejtovi ne mogu biti instancirani
## Definisanje trejta
Minimalni trejt je samo ključna riječ `trait` i identifikator:
-```tut
+```scala mdoc
trait HairColor
```
Trejtovi su vrlo korisni s generičkim tipovima i apstraktnim metodama.
-```tut
+```scala mdoc
trait Iterator[A] {
def hasNext: Boolean
def next(): A
@@ -37,7 +34,7 @@ Nasljeđivanje `trait Iterator[A]` traži tip `A` i implementacije metoda `hasNe
## Korištenje trejtova
Koristite `extends` za nasljeđivanje trejta. Zatim implementirajte njegove apstraktne članove koristeći `override` ključnu riječ:
-```tut
+```scala mdoc:nest
trait Iterator[A] {
def hasNext: Boolean
def next(): A
@@ -65,7 +62,7 @@ Ona nasljeđuje `Iterator[Int]` što znači da `next` mora vraćati `Int`.
## Podtipovi
Podtipovi trejtova mogu se koristiti gdje se trejt traži.
-```tut
+```scala mdoc
import scala.collection.mutable.ArrayBuffer
trait Pet {
diff --git a/_ba/tour/tuples.md b/_ba/tour/tuples.md
new file mode 100644
index 0000000000..99f49e7247
--- /dev/null
+++ b/_ba/tour/tuples.md
@@ -0,0 +1,13 @@
+---
+layout: tour
+title: Tuples
+language: ba
+partof: scala-tour
+num:
+next-page: mixin-class-composition
+previous-page: traits
+
+---
+
+(this section of the tour has not been translated yet. pull request
+with translation welcome!)
diff --git a/_ba/tour/type-inference.md b/_ba/tour/type-inference.md
index 926c3a4feb..d3b7eb1867 100644
--- a/_ba/tour/type-inference.md
+++ b/_ba/tour/type-inference.md
@@ -2,9 +2,6 @@
layout: tour
title: Lokalno zaključivanje tipova (type inference)
language: ba
-
-discourse: true
-
partof: scala-tour
num: 29
@@ -19,7 +16,7 @@ Povratni tipovi metoda također mogu biti izostavljeni jer oni odgovaraju tipu t
Slijedi jedan primjer:
-```tut
+```scala mdoc
object InferenceTest1 extends App {
val x = 1 + 2 * 3 // the type of x is Int
val y = x.toString() // the type of y is String
@@ -30,7 +27,7 @@ object InferenceTest1 extends App {
Za rekurzivne metode, kompajler nije u mogućnosti da zaključi tip rezultata.
Ovo je program koji se ne može kompajlirati iz ovog razloga:
-```tut:fail
+```scala mdoc:fail
object InferenceTest2 {
def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1)
}
@@ -43,7 +40,7 @@ Scala kompajler će zaključiti nedostajuće tipske parametre iz konteksta i iz
Ovo je primjer koji to ilustrira:
```
-case class MyPair[A, B](x: A, y: B);
+case class MyPair[A, B](x: A, y: B)
object InferenceTest3 extends App {
def id[T](x: T) = x
val p = MyPair(1, "scala") // type: MyPair[Int, String]
@@ -61,7 +58,7 @@ val y: Int = id[Int](1)
U nekim situacijama može biti vrlo opasno osloniti se na Scalin mehanizam zaključivanja tipova:
-```tut:fail
+```scala mdoc:fail
object InferenceTest4 {
var obj = null
obj = new Object()
diff --git a/_ba/tour/unified-types.md b/_ba/tour/unified-types.md
index 44af9e748e..92c1e2a61e 100644
--- a/_ba/tour/unified-types.md
+++ b/_ba/tour/unified-types.md
@@ -2,9 +2,6 @@
layout: tour
title: Sjedinjeni tipovi
language: ba
-
-discourse: true
-
partof: scala-tour
num: 3
@@ -21,14 +18,14 @@ Dijagram ispod prikazuje hijerarhiju Scala klasa.
## Hijerarhija tipova u Scali ##
-[`Any`](http://www.scala-lang.org/api/2.12.1/scala/Any.html) je nadtip svih tipova, zove se još i vrh-tip.
+[`Any`](https://www.scala-lang.org/api/2.12.1/scala/Any.html) je nadtip svih tipova, zove se još i vrh-tip.
Definiše određene univerzalne metode kao što su `equals`, `hashCode` i `toString`.
`Any` ima dvije direktne podklase, `AnyVal` i `AnyRef`.
-`AnyVal` predstavlja vrijednosne tipove. Postoji devet predefinisanih vrijednosnih tipova i oni ne mogu biti `null`:
+`AnyVal` predstavlja vrijednosne tipove. Postoji devet predefinisanih vrijednosnih tipova i oni ne mogu biti `null`:
`Double`, `Float`, `Long`, `Int`, `Short`, `Byte`, `Char`, `Unit` i `Boolean`.
-`Unit` je vrijednosni tip koji ne nosi značajnu informaciju. Postoji tačno jedna instanca tipa `Unit` koja se piše `()`.
+`Unit` je vrijednosni tip koji ne nosi značajnu informaciju. Postoji tačno jedna instanca tipa `Unit` koja se piše `()`.
Sve funkcije moraju vratiti nešto tako da je `Unit` ponekad koristan povratni tip.
`AnyRef` predstavlja referencne tipove. Svi nevrijednosni tipovi definišu se kao referencni.
@@ -37,7 +34,7 @@ Ako se Scala koristi u kontekstu JRE, onda `AnyRef` odgovara klasi `java.lang.Ob
Slijedi primjer koji demonstrira da su stringovi, integeri, karakteri, booleani i funkcije svi objekti kao bilo koji drugi:
-```tut
+```scala mdoc
val list: List[Any] = List(
"a string",
732, // an integer
@@ -67,9 +64,9 @@ Vrijednosni tipovi mogu biti kastovani na sljedeći način:
Npr:
-```tut
+```scala mdoc
val x: Long = 987654321
-val y: Float = x // 9.8765434E8 (određena doza preciznosti se gubi ovdje)
+val y: Float = x.toFloat // 9.8765434E8 (određena doza preciznosti se gubi ovdje)
val face: Char = '☺'
val number: Int = face // 9786
@@ -79,17 +76,17 @@ Kastovanje je jednosmjerno. Ovo se ne kompajlira:
```
val x: Long = 987654321
-val y: Float = x // 9.8765434E8
+val y: Float = x.toFloat // 9.8765434E8
val z: Long = y // Does not conform
```
Također možete kastovati i referencni tip u podtip. Ovo će biti pokriveno kasnije.
## Nothing i Null
-`Nothing` je podtip svih tipova, također se zove i donji tip (en. bottom type). Ne postoji vrijednost koja ima tip `Nothing`.
+`Nothing` je podtip svih tipova, također se zove i donji tip (en. bottom type). Ne postoji vrijednost koja ima tip `Nothing`.
Česta upotreba ovog tipa je signalizacija neterminacije kao što je bacanje izuzetka, izlaz iz programa, ili beskonačna petlja (tj. tip izraza koji se ne izračunava u vrijednost, ili metoda koja se ne završava normalno).
-`Null` je podtip svih referencnih tipova (tj. bilo kog podtipa `AnyRef`).
-Ima jednu vrijednost koja se piše literalom `null`.
-`Null` se uglavnom koristi radi interoperabilnosti s ostalim JVM jezicima i skoro nikad se ne koristi u Scala kodu.
+`Null` je podtip svih referencnih tipova (tj. bilo kog podtipa `AnyRef`).
+Ima jednu vrijednost koja se piše literalom `null`.
+`Null` se uglavnom koristi radi interoperabilnosti s ostalim JVM jezicima i skoro nikad se ne koristi u Scala kodu.
Alternative za `null` obradićemo kasnije.
diff --git a/_ba/tour/upper-type-bounds.md b/_ba/tour/upper-type-bounds.md
index b8afa51ee2..e91d904d5d 100644
--- a/_ba/tour/upper-type-bounds.md
+++ b/_ba/tour/upper-type-bounds.md
@@ -2,9 +2,6 @@
layout: tour
title: Gornja granica tipa
language: ba
-
-discourse: true
-
partof: scala-tour
categories: tour
num: 20
@@ -13,12 +10,12 @@ previous-page: variances
---
-U Scali, [tipski parametri](generic-classes.html) i [apstraktni tipovi](abstract-types.html) mogu biti ograničeni granicom tipa.
+U Scali, [tipski parametri](generic-classes.html) i [apstraktni tipovi](abstract-type-members.html) mogu biti ograničeni granicom tipa.
Takve granice tipa ograničavaju konkretne vrijednosti tipskih varijabli i ponekad otkrivaju još informacija o članovima takvih tipova.
_Gornja granica tipa_ `T <: A` kaže da se tipska varijabla `T` odnosi na podtip tipa `A`.
Slijedi primjer koji demonstrira gornju granicu tipa za tipski parametar klase `PetContainer`:
-```tut
+```scala mdoc
abstract class Animal {
def name: String
}
@@ -45,7 +42,7 @@ val dogContainer = new PetContainer[Dog](new Dog)
val catContainer = new PetContainer[Cat](new Cat)
```
-```tut:fail
+```scala mdoc:fail
val lionContainer = new PetContainer[Lion](new Lion) // this would not compile
```
Klasa `PetContainer` prima tipski parametar `P` koji mora biti podtip od `Pet`.
diff --git a/_ba/tour/variances.md b/_ba/tour/variances.md
index a1f955543a..2920e00dac 100644
--- a/_ba/tour/variances.md
+++ b/_ba/tour/variances.md
@@ -2,9 +2,6 @@
layout: tour
title: Varijanse
language: ba
-
-discourse: true
-
partof: scala-tour
num: 19
@@ -17,7 +14,7 @@ Varijansa je korelacija podtipskih veza kompleksnih tipova i podtipskih veza nji
Scala podržava anotacije varijanse tipskih parametara [generičkih klasa](generic-classes.html), dozvoljavajući im da budu kovarijantni, kontravarijantni, ili invarijantni ako se anotacije ne koriste.
Korištenje varijanse u sistemu tipova dozvoljava pravljenje intuitivnijih veza među kompleksnim tipovima, a nedostatak varijanse može ograničiti ponovno iskorištenje klasne apstrakcije.
-```tut
+```scala mdoc
class Foo[+A] // kovarijantna klasa
class Bar[-A] // kontravarijantna klasa
class Baz[A] // invarijantna klasa
@@ -31,7 +28,7 @@ Ovo dozvoljava pravljenje vrlo intuitivnih podtipskih veza koristeći generiku.
Razmotrite sljedeću strukturu klasa:
-```tut
+```scala mdoc
abstract class Animal {
def name: String
}
@@ -47,7 +44,7 @@ Intuitivno, ima smisla da su lista mačaka i lista pasa također liste životinj
U sljedećem primjeru, metoda `printAnimalNames` prima listu životinja kao argument i ispisuje njihova imena, svako na idućoj liniji.
Da `List[A]` nije kovarijantna, zadnja dva poziva metode se ne bi kompajlirali, što bi značajno ograničilo korisnost `printAnimalNames` metode.
-```tut
+```scala mdoc
object CovarianceTest extends App {
def printAnimalNames(animals: List[Animal]): Unit = {
animals.foreach { animal =>
@@ -76,7 +73,7 @@ To jest, za neku `class Writer[-A]`, kontravarijantno `A` znači da za dva tipa
Razmotrimo `Cat`, `Dog`, i `Animal` klase u sljedećem primjeru:
-```tut
+```scala mdoc
abstract class Printer[-A] {
def print(value: A): Unit
}
@@ -84,7 +81,7 @@ abstract class Printer[-A] {
`Printer[A]` je jednostavna klasa koja zna ispisati neki tip `A`. Definišimo neke podklase za specifične tipove:
-```tut
+```scala mdoc
class AnimalPrinter extends Printer[Animal] {
def print(animal: Animal): Unit =
println("The animal's name is: " + animal.name)
@@ -102,7 +99,7 @@ Inverzna veza ne vrijedi, jer `Printer[Cat]` ne zna kako da ispiše bilo koju `A
Stoga, terbali bismo moći zamijeniti `Printer[Animal]` za `Printer[Cat]`, ako želimo, i praveći `Printer[A]` kontravarijantnim nam to dozvoljava.
-```tut
+```scala mdoc
object ContravarianceTest extends App {
val myCat: Cat = Cat("Boots")
@@ -132,7 +129,7 @@ Ovo znač da nisu ni kovarijantne ni kontravarijantne.
U kontekstu sljedećeg primjera, `Container` klasa je invarijantna.
`Container[Cat]` _nije_ `Container[Animal]`, niti obrnuto.
-```tut
+```scala mdoc
class Container[A](value: A) {
private var _value: A = value
def getValue: A = _value
@@ -165,7 +162,7 @@ Za ovaj primjer koristićemo literal notaciju `A => B` za predstavljanje `Functi
Pretpostavimo da imamo sličnu hijerarhiju klasa `Cat`, `Dog`, `Animal` otprije, plus sljedeće:
-```tut
+```scala mdoc
class SmallAnimal
class Mouse extends SmallAnimal
```
diff --git a/_books/1-programming-in-scala-3rd.md b/_books/1-programming-in-scala-3rd.md
deleted file mode 100644
index 4c04d132c8..0000000000
--- a/_books/1-programming-in-scala-3rd.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-title: "Programming in Scala, 3rd ed"
-link: http://booksites.artima.com/programming_in_scala_3ed
-image: /resources/img/books/ProgrammingInScala.gif
-status: Updated for Scala 2.12
-authors: ["Martin Odersky", "Lex Spoon", "Bill Benners"]
-publisher:
----
-
-(First edition [available for free online reading](http://www.artima.com/pins1ed/))
-
-Being co-written by the language's designer, Martin Odersky, you will find it provides additional depth and clarity to the diverse features of the language. The book provides both an authoritative reference for Scala and a systematic tutorial covering all the features in the language. Once you are familiar with the basics of Scala you will appreciate having this source of invaluable examples and precise explanations of Scala on hand. The book is available from [Artima](http://booksites.artima.com/programming_in_scala_3ed). Award winning book - [Jolt Productivity award](http://www.drdobbs.com/joltawards/232601431) for Technical Books.
diff --git a/_books/1-programming-in-scala-5th.md b/_books/1-programming-in-scala-5th.md
new file mode 100644
index 0000000000..826e5361df
--- /dev/null
+++ b/_books/1-programming-in-scala-5th.md
@@ -0,0 +1,11 @@
+---
+title: "Programming in Scala, 5th ed"
+link: https://www.artima.com/shop/programming_in_scala_5ed
+image: /resources/img/books/ProgrammingInScala.png
+status: Updated for Scala 3
+authors: ["Martin Odersky", "Lex Spoon", "Bill Venners"]
+publisher: Artima
+publisherLink: https://www.artima.com/books
+---
+
+This book is co-authored by the language's designer, Martin Odersky. It provides depth and clarity on the diverse features of the language. The book provides both an authoritative reference for Scala and a systematic tutorial covering all the features in the language. Once you are familiar with the basics of Scala you will appreciate having this source of invaluable examples and precise explanations of Scala on hand. The book is available from [Artima](https://www.artima.com/shop/programming_in_scala_5ed). Award winning book - [Jolt Productivity award](https://www.drdobbs.com/joltawards/232601431) for Technical Books.
diff --git a/_books/2-programming-scala.md b/_books/2-programming-scala.md
new file mode 100644
index 0000000000..8fc729169f
--- /dev/null
+++ b/_books/2-programming-scala.md
@@ -0,0 +1,11 @@
+---
+title: "Programming Scala"
+link: http://programming-scala.com
+image: /resources/img/books/ProgrammingScala-final-border.gif
+status: Updated for Scala 3
+authors: ["Dean Wampler"]
+publisher: O’Reilly
+publisherLink: https://www.oreilly.com/
+---
+
+Dean is a well-known member of the Scala community, using Scala recently for streaming data systems at Lightbend and now at Domino Data Lab. This edition covers the new features of Scala 3, with comparisons to Scala 2, both to explain why the changes were made and how they improve Scala, and also to enable developers using mixed Scala 2 and 3 code bases to work effectively. The book is aimed at professional programmers who want a comprehensive, in-depth, yet pragmatic tour of Scala and best practices for using it.
diff --git a/_books/3-programming-scala.md b/_books/3-programming-scala.md
deleted file mode 100644
index eb814ff1fb..0000000000
--- a/_books/3-programming-scala.md
+++ /dev/null
@@ -1,11 +0,0 @@
----
-title: "Programming Scala"
-link: http://shop.oreilly.com/product/0636920033073.do
-image: /resources/img/books/ProgrammingScala-final-border.gif
-status: Updated for Scala 2.11
-authors: ["Alex Payne", "Dean Wampler"]
-publisher: O’Reilly
-publisherLink: http://www.oreilly.com/
----
-
-Both are industry experts, Alex Payne being the lead API programmer at Twitter, a social networking service based on Scala. O’Reilly, the publisher, writes: "Learn how to be more productive with Scala, a new multi-paradigm language for the Java Virtual Machine (JVM) that integrates features of both object-oriented and functional programming. With this book, you'll discover why Scala is ideal for highly scalable, component-based applications that support concurrency and distribution. You'll also learn how to leverage the wealth of Java class libraries to meet the practical needs of enterprise and Internet projects more easily."
\ No newline at end of file
diff --git a/_books/2-scala-for-the-impatient.md b/_books/3-scala-for-the-impatient.md
similarity index 56%
rename from _books/2-scala-for-the-impatient.md
rename to _books/3-scala-for-the-impatient.md
index 41e63d0c1d..72c7c01f6d 100644
--- a/_books/2-scala-for-the-impatient.md
+++ b/_books/3-scala-for-the-impatient.md
@@ -1,15 +1,17 @@
---
title: "Scala for the Impatient"
-link: http://www.horstmann.com/scala/index.html
-image: /resources/img/books/scala_for_the_impatient.png
-status: Available Now
-authors: ["Cay S. Horstmann"]
-publisher: Addison-Wesley
+link: https://horstmann.com/scala/
+image: /resources/img/books/scala_for_the_impatient.jpg
+status: Updated for Scala 3
+authors: ["Cay Horstmann"]
+publisher: Addison-Wesley Professional
+publisherLink: https://www.oreilly.com/publisher/addison-wesley-professional/
---
What you get:
-* A rapid introduction to Scala for programmers who are competent in Java, C#, or C++
+* Up to date coverage of Scala 3
+* A rapid introduction to Scala for programmers who are competent in another language such as Java, C#, Python, JavaScript, or C++
* Blog-length chunks of information that you can digest quickly
* An organization that you'll find useful as a quick reference
diff --git a/_books/4-hands-on-scala.md b/_books/4-hands-on-scala.md
new file mode 100644
index 0000000000..ba60fbf9b6
--- /dev/null
+++ b/_books/4-hands-on-scala.md
@@ -0,0 +1,11 @@
+---
+title: "Hands-on Scala Programming"
+link: https://www.handsonscala.com/
+image: /resources/img/books/HandsOnScala.jpg
+status: Covers Scala 2.13
+authors: ["Li Haoyi"]
+publisher: Li Haoyi
+publisherLink: http://www.lihaoyi.com
+---
+
+"Hands-on Scala teaches you how to use the Scala programming language in a practical, project-based fashion. This book is designed to quickly teach an existing programmer everything needed to go from "hello world" to building production applications like interactive websites, parallel web crawlers, and distributed systems in Scala. In the process you will learn how to use the Scala language to solve challenging problems in an elegant and intuitive manner."
diff --git a/_books/5-get-programming.md b/_books/5-get-programming.md
new file mode 100644
index 0000000000..5d6803860d
--- /dev/null
+++ b/_books/5-get-programming.md
@@ -0,0 +1,11 @@
+---
+title: "Get Programming with Scala"
+link: https://www.manning.com/books/get-programming-with-scala
+image: /resources/img/books/get-programming-book.png
+status: Covers Scala 2 and 3
+authors: ["Daniela Sfregola"]
+publisher: Manning
+publisherLink: https://www.manning.com/
+---
+
+"The perfect starting point for your journey into Scala and functional programming. Scala is a multi-style programming language for the JVM that supports both object-oriented and functional programming. Master Scala, and you'll be well-equipped to match your programming approach to the type of problem you're dealing with. Packed with examples and exercises, _Get Programming with Scala_ is the perfect starting point for developers with some OO knowledge who want to learn Scala and pick up a few FP skills along the way."
diff --git a/_books/5-scala-in-depth.md b/_books/5-scala-in-depth.md
deleted file mode 100644
index 6262e3a4ee..0000000000
--- a/_books/5-scala-in-depth.md
+++ /dev/null
@@ -1,11 +0,0 @@
----
-title: "Scala in Depth"
-link: http://www.manning.com/suereth
-image: /resources/img/books/icon_Scala_in_Depth_93x116.png
-status: Available now
-authors: ["Joshua D. Suereth"]
-publisher: Manning
-publisherLink: http://www.manning.com/
----
-
-"While information about the Scala language is abundant, skilled practitioners, great examples, and insight into the best practices of the community are harder to find. Scala in Depth bridges that gap, preparing you to adopt Scala successfully for real world projects. Scala in Depth is a unique new book designed to help you integrate Scala effectively into your development process. By presenting the emerging best practices and designs from the Scala community, it guides you though dozens of powerful techniques example by example. There's no heavy-handed theory here-just lots of crisp, practical guides for coding in Scala."
\ No newline at end of file
diff --git a/_books/6-creative-scala.md b/_books/6-creative-scala.md
new file mode 100644
index 0000000000..bd2007679a
--- /dev/null
+++ b/_books/6-creative-scala.md
@@ -0,0 +1,11 @@
+---
+title: "Creative Scala"
+link: https://www.creativescala.org
+image: /resources/img/books/CreativeScala.png
+status: Free online book
+authors: ["Dave Gurnell", "Noel Welsh"]
+publisher: Underscore
+publisherLink: https://underscore.io
+---
+
+"The book for new developers who want to learn Scala and have fun. Creative Scala is aimed at developers who have no prior experience in Scala. It is designed to give you a fun introduction to functional programming. We assume you have some very basic familiarity with another programming language but little or no experience with Scala or other functional languages. We've chosen what we hope is a fun method to explore functional programming and Scala: computer graphics."
diff --git a/_books/6-scala-puzzlers.md b/_books/6-scala-puzzlers.md
deleted file mode 100644
index 13b54f555e..0000000000
--- a/_books/6-scala-puzzlers.md
+++ /dev/null
@@ -1,11 +0,0 @@
----
-title: "Scala Puzzlers"
-link: http://www.artima.com/shop/scala_puzzlers
-image: /resources/img/books/scala-puzzlers-book.jpg
-status: Available now
-authors: ["Andrew Phillips", "Nermin Šerifović"]
-publisher: Artima Press
-publisherLink: http://www.artima.com/index.jsp
----
-
-"Getting code to do what we want it to do is perhaps the essence of our purpose as developers. So there are few things more intriguing or important than code that we think we understand, but that behaves rather contrary to our expectations. Scala Puzzlers is a collection of such examples in Scala. It is not only an entertaining and instructive way of understanding this highly expressive language better. It will also help you recognize many counter-intuitive traps and pitfalls and prevent them from inflicting further production bug hunt stress on Scala developers."
diff --git a/_books/4-functional-programming-in-scala.md b/_books/7-functional-programming-in-scala.md
similarity index 67%
rename from _books/4-functional-programming-in-scala.md
rename to _books/7-functional-programming-in-scala.md
index 9a27404679..0b878c6b15 100644
--- a/_books/4-functional-programming-in-scala.md
+++ b/_books/7-functional-programming-in-scala.md
@@ -1,11 +1,13 @@
---
title: "Functional Programming in Scala"
-link: https://www.manning.com/books/functional-programming-in-scala
-image: /resources/img/books/FPiS_93x116.png
-status: Available now
-authors: ["Paul Chiusano", "Rúnar Bjarnason"]
+link: https://www.manning.com/books/functional-programming-in-scala-second-edition
+image: /resources/img/books/FPiS_93x116.jpg
+status: Updated for Scala 3
+authors: ["Michael Pilquist", "Paul Chiusano", "Rúnar Bjarnason"]
publisher: Manning
-publisherLink: http://www.manning.com/
+publisherLink: https://www.manning.com/
---
-"Functional programming (FP) is a style of software development emphasizing functions that don't depend on program state... Functional Programming in Scala is a serious tutorial for programmers looking to learn FP and apply it to the everyday business of coding. The book guides readers from basic techniques to advanced topics in a logical, concise, and clear progression. In it, you'll find concrete examples and exercises that open up the world of functional programming."
\ No newline at end of file
+"Functional programming (FP) is a style of software development emphasizing functions that don't depend on program state... Functional Programming in Scala is a serious tutorial for programmers looking to learn FP and apply it to the everyday business of coding. The book guides readers from basic techniques to advanced topics in a logical, concise, and clear progression. In it, you'll find concrete examples and exercises that open up the world of functional programming."
+
+Forewords by Daniel Spiewak and Martin Odersky.
diff --git a/_cheatsheets/index.md b/_cheatsheets/index.md
new file mode 100644
index 0000000000..679e4ed242
--- /dev/null
+++ b/_cheatsheets/index.md
@@ -0,0 +1,622 @@
+---
+layout: cheatsheet
+title: Scala Cheatsheet
+
+partof: cheatsheet
+
+by: Brendan O'Connor
+about: Thanks to Brendan O'Connor, this cheatsheet aims to be a quick reference of Scala syntactic constructions. Licensed by Brendan O'Connor under a CC-BY-SA 3.0 license.
+
+languages: [ba, fr, ja, pl, pt-br, zh-cn, th, ru, uk]
+---
+
+
+
+{{ page.about }}
+
+
+
+
+
+
+
+
+
variables
+
+
+
+
var x = 5
Good
x = 6
+
Variable.
+
+
+
val x = 5
Bad
x = 6
+
Constant.
+
+
+
var x: Double = 5
+
Explicit type.
+
+
+
functions
+
+
+
+
Good
def f(x: Int) = { x * x }
Bad
def f(x: Int) { x * x }
+
Define function. Hidden error: without = it’s a procedure returning Unit; causes havoc. Deprecated in Scala 2.13.
+
+
+
Good
def f(x: Any) = println(x)
Bad
def f(x) = println(x)
+
Define function. Syntax error: need types for every arg.
+
+
+
type R = Double
+
Type alias.
+
+
+
def f(x: R)
vs.
def f(x: => R)
+
Call-by-value.
Call-by-name (lazy parameters).
+
+
+
(x: R) => x * x
+
Anonymous function.
+
+
+
(1 to 5).map(_ * 2)
vs.
(1 to 5).reduceLeft(_ + _)
+
Anonymous function: underscore is positionally matched arg.
+
+
+
(1 to 5).map(x => x * x)
+
Anonymous function: to use an arg twice, have to name it.
+
+
+
(1 to 5).map { x =>
+ val y = x * 2
+ println(y)
+ y
+}
+
Anonymous function: block style returns last expression.
For-comprehension: iterate including the upper bound.
+
+
+
for (i <- 1 until 5) {
+ println(i)
+}
+
For-comprehension: iterate omitting the upper bound.
+
+
+
pattern matching
+
+
+
+
Good
(xs zip ys) map {
+ case (x, y) => x * y
+}
Bad
(xs zip ys) map {
+ (x, y) => x * y
+}
+
Use case in function args for pattern matching.
+
+
+
Bad
+
val v42 = 42
+3 match {
+ case v42 => println("42")
+ case _ => println("Not 42")
+}
+
v42 is interpreted as a name matching any Int value, and “42” is printed.
+
+
+
Good
+
val v42 = 42
+3 match {
+ case `v42` => println("42")
+ case _ => println("Not 42")
+}
+
`v42` with backticks is interpreted as the existing val v42, and “Not 42” is printed.
+
+
+
Good
+
val UppercaseVal = 42
+3 match {
+ case UppercaseVal => println("42")
+ case _ => println("Not 42")
+}
+
UppercaseVal is treated as an existing val, rather than a new pattern variable, because it starts with an uppercase letter. Thus, the value contained within UppercaseVal is checked against 3, and “Not 42” is printed.
+
+
+
object orientation
+
+
+
+
class C(x: R)
+
Constructor params - x is only available in class body.
+
+
+
class C(val x: R)
var c = new C(4)
c.x
+
Constructor params - automatic public member defined.
+
+
+
class C(var x: R) {
+ assert(x > 0, "positive please")
+ var y = x
+ val readonly = 5
+ private var secret = 1
+ def this() = this(42)
+}
+
Constructor is class body. Declare a public member. Declare a gettable but not settable member. Declare a private member. Alternative constructor.
+
+
+
new {
+ ...
+}
+
Anonymous class.
+
+
+
abstract class D { ... }
+
Define an abstract class (non-createable).
+
+
+
class C extends D { ... }
+
Define an inherited class.
+
+
+
class D(var x: R)
class C(x: R) extends D(x)
+
Inheritance and constructor params (wishlist: automatically pass-up params by default).
+
+
+
object O extends D { ... }
+
Define a singleton (module-like).
+
+
+
trait T { ... }
class C extends T { ... }
class C extends D with T { ... }
+
Traits. Interfaces-with-implementation. No constructor params. mixin-able.
+
+
+
trait T1; trait T2
class C extends T1 with T2
class C extends D with T1 with T2
+
Multiple traits.
+
+
+
class C extends D { override def f = ...}
+
Must declare method overrides.
+
+
+
new java.io.File("f")
+
Create object.
+
+
+
Bad
new List[Int]
Good
List(1, 2, 3)
+
Type error: abstract type. Instead, convention: callable factory shadowing the type.
+
+
+
classOf[String]
+
Class literal.
+
+
+
x.isInstanceOf[String]
+
Type check (runtime).
+
+
+
x.asInstanceOf[String]
+
Type cast (runtime).
+
+
+
x: String
+
Ascription (compile time).
+
+
+
+
options
+
+
+
+
Some(42)
+
Construct a non empty optional value.
+
+
+
None
+
The singleton empty optional value.
+
+
+
Option(null) == None
+Option(obj.unsafeMethod)
+ but
+
Some(null) != None
+
Null-safe optional value factory.
+
+
+
val optStr: Option[String] = None
+ same as
+
val optStr = Option.empty[String]
+
Explicit type for empty optional value. Factory for empty optional value.
+ scala コマンドはソーススクリプトをテンプレートでラップし、コンパイルし、できあがったプログラムを実行することで実行する。
+ - title: Scaladoc
+ url: "scaladoc/overview.html"
+ icon: book
+ description: "Scala の API ドキュメント生成ツール"
+ subdocs:
+ - title: 概要
+ url: "scaladoc/overview.html"
+ - title: ライブラリ作者のための Scaladoc
+ url: "scaladoc/for-library-authors.html"
+ - title: Scaladoc インターフェースを使う
+ url: "scaladoc/interface.html"
+
+- category: コンパイラー
+ description: "Scala コンパイラーをカバーするガイドと概要。コンパイラプラグイン、リフレクション、マクロのようなメタプログラミング。"
+ overviews:
+ - title: リフレクション
+ by: Heather Miller, Eugene Burmako, and Philipp Haller
+ icon: binoculars
+ url: "reflection/overview.html"
+ description: Scala の実行時/コンパイル時のリフレクションフレームワーク。
+ label-text: experimental
+ subdocs:
+ - title: 概要
+ url: "reflection/overview.html"
+ - title: 環境、ユニバース、ミラー
+ url: "reflection/environment-universes-mirrors.html"
+ - title: シンボル、構文木、型
+ url: "reflection/symbols-trees-types.html"
+ - title: アノテーション、名前、スコープ、その他
+ url: "reflection/annotations-names-scopes.html"
+ - title: 型タグとマニフェスト
+ url: "reflection/typetags-manifests.html"
+ - title: スレッドセーフティ
+ url: "reflection/thread-safety.html"
+ - title: Scala 2.11 での変更
+ url: "reflection/changelog211.html"
+ - title: マクロ
+ by: Eugene Burmako
+ icon: magic
+ url: "macros/usecases.html"
+ description: "Scala のメタプログラミングフレームワーク"
+ label-text: experimental
+ subdocs:
+ - title: ユースケース
+ url: "macros/usecases.html"
+ - title: Blackbox vs Whitebox
+ url: "macros/blackbox-whitebox.html"
+ - title: def マクロ
+ url: "macros/overview.html"
+ - title: 準クォート
+ url: "quasiquotes/intro.html"
+ - title: マクロバンドル
+ url: "macros/bundles.html"
+ - title: implicit マクロ
+ url: "macros/implicits.html"
+ - title: 抽出子マクロ
+ url: "macros/extractors.html"
+ - title: 型プロバイダ
+ url: "macros/typeproviders.html"
+ - title: マクロアノテーション
+ url: "macros/annotations.html"
+ - title: マクロパラダイス
+ url: "macros/paradise.html"
+ - title: ロードマップ
+ url: "macros/roadmap.html"
+ - title: Scala 2.11 での変更
+ url: "macros/changelog211.html"
+ - title: 準クォート
+ by: Denys Shabalin
+ icon: quote-left
+ url: "quasiquotes/setup.html"
+ description: "準クォートは Scala の構文木を操作する便利な方法だ。"
+ label-text: experimental
+ subdocs:
+ - title: 依存関係とセットアップ
+ url: "quasiquotes/setup.html"
+ - title: はじめに
+ url: "quasiquotes/intro.html"
+ - title: リフト
+ url: "quasiquotes/lifting.html"
+ - title: アンリフト
+ url: "quasiquotes/unlifting.html"
+ - title: 健全性
+ url: "quasiquotes/hygiene.html"
+ - title: ユースケース
+ url: "quasiquotes/usecases.html"
+ - title: 構文の概要
+ url: "quasiquotes/syntax-summary.html"
+ - title: 式の詳細
+ url: "quasiquotes/expression-details.html"
+ - title: 型の詳細
+ url: "quasiquotes/type-details.html"
+ - title: パターンの詳細
+ url: "quasiquotes/pattern-details.html"
+ - title: 定義とインポートの詳細
+ url: "quasiquotes/definition-details.html"
+ - title: 専門用語の概要
+ url: "quasiquotes/terminology.html"
+ - title: 将来の見通し
+ url: "quasiquotes/future.html"
+ - title: コンパイラープラグイン
+ by: Lex Spoon and Seth Tisue
+ icon: puzzle-piece
+ url: "plugins/index.html"
+ description: "コンパイラープラグインは Scala コンパイラーのカスタマイズと拡張を可能にする。このチュートリアルはプラグインの仕組みを説明し、かんたんなプラグインの作成をウォークスルーする。"
+ - title: コンパイラーオプション
+ by: Community
+ icon: cog
+ url: "compiler-options/index.html"
+ description: >
+ scalac がどのようにコードをコンパイルするかの様々な設定。
+
+
+- category: レガシー
+ description: "最近の Scala バージョン(2.12以上)には関係なくなった機能をカバーするガイド。"
+ overviews:
+ - title: Scala 2.8 から 2.12 までのコレクション
+ by: Martin Odersky
+ icon: sitemap
+ url: "collections/introduction.html"
+ description: "Scala's Collection Library."
+ subdocs:
+ - title: はじめに
+ url: "collections/introduction.html"
+ - title: 可変コレクションおよび不変コレクション
+ url: "collections/overview.html"
+ - title: Traversable トレイト
+ url: "collections/trait-traversable.html"
+ - title: Iterable トレイト
+ url: "collections/trait-iterable.html"
+ - title: 列トレイト Seq、IndexedSeq、および LinearSeq
+ url: "collections/seqs.html"
+ - title: 集合
+ url: "collections/sets.html"
+ - title: マップ
+ url: "collections/maps.html"
+ - title: 具象不変コレクションクラス
+ url: "collections/concrete-immutable-collection-classes.html"
+ - title: 具象可変コレクションクラス
+ url: "collections/concrete-mutable-collection-classes.html"
+ - title: 配列
+ url: "collections/arrays.html"
+ - title: 文字列
+ url: "collections/strings.html"
+ - title: 性能特性
+ url: "collections/performance-characteristics.html"
+ - title: 等価性
+ url: "collections/equality.html"
+ - title: ビュー
+ url: "collections/views.html"
+ - title: イテレータ
+ url: "collections/iterators.html"
+ - title: コレクションの作成
+ url: "collections/creating-collections-from-scratch.html"
+ - title: Java と Scala 間のコレクションの変換
+ url: "collections/conversions-between-java-and-scala-collections.html"
+ - title: Scala 2.7 からの移行
+ url: "collections/migrating-from-scala-27.html"
+ - title: Scala 2.8 から 2.12 までのコレクションのアーキテクチャ
+ icon: building
+ url: "core/architecture-of-scala-collections.html"
+ by: Martin Odersky and Lex Spoon
+ description: "これらのページは Scala コレクションフレームワークのアーキテクチャを詳細に説明する。コレクション API というよりはフレームワークの内部の動きがもっとよく分かるだろう。また、コレクションフレームワークがどのようにして数行のコードであなた自身が独自コレクションを定義でき、しかもフレームワークの圧倒的な量の機能を再利用できる助けをしているかを学べるだろう。"
diff --git a/_data/overviews-ru.yml b/_data/overviews-ru.yml
new file mode 100644
index 0000000000..f4a652a032
--- /dev/null
+++ b/_data/overviews-ru.yml
@@ -0,0 +1,307 @@
+- category: Стандартная Библиотека
+ description: "Руководства и обзоры, охватывающие стандартную библиотеку Scala."
+ overviews:
+ - title: Scala коллекции
+ by: Martin Odersky и Julien Richard-Foy
+ icon: sitemap
+ url: "collections-2.13/introduction.html"
+ description: "Библиотека Scala коллекций."
+ subdocs:
+ - title: Введение
+ url: "collections-2.13/introduction.html"
+ - title: Изменяемые и Неизменяемые Коллекции
+ url: "collections-2.13/overview.html"
+ - title: Трейт Iterable
+ url: "collections-2.13/trait-iterable.html"
+ - title: Последовательности. Трейты Seq, IndexedSeq и LinearSeq
+ url: "collections-2.13/seqs.html"
+ - title: Реализации Неизменяемых Коллекций
+ url: "collections-2.13/concrete-immutable-collection-classes.html"
+ - title: Реализации Изменяемых Коллекций
+ url: "collections-2.13/concrete-mutable-collection-classes.html"
+ - title: Массивы
+ url: "collections-2.13/arrays.html"
+ - title: Строки
+ url: "collections-2.13/strings.html"
+ - title: Показатели производительности
+ url: "collections-2.13/performance-characteristics.html"
+ - title: Равенство
+ url: "collections-2.13/equality.html"
+ - title: Отображения
+ url: "collections-2.13/views.html"
+ - title: Итераторы
+ url: "collections-2.13/iterators.html"
+ - title: Создание коллекций с нуля
+ url: "collections-2.13/creating-collections-from-scratch.html"
+ - title: Преобразования между Java и Scala коллекциями
+ url: "collections-2.13/conversions-between-java-and-scala-collections.html"
+ - title: Перевод проекта на использование коллекций Scala 2.13
+ icon: sitemap
+ url: "core/collections-migration-213.html"
+ description: "Эта страница описывает главные изменения в коллекциях для тех кто
+ переводит проект на Scala 2.13, а также демонстрирует как собирать проект под версии Scala 2.11 / 2.12 и 2.13"
+ - title: Архитектура Scala коллекций
+ icon: sitemap
+ url: "core/architecture-of-scala-213-collections.html"
+ by: Julien Richard-Foy
+ description: "На этих страницах описывается архитектура фреймворка коллекций, представленного в Scala 2.13. По сравнению с API Коллекции вы узнаете здесь больше о внутренней работе фреймворка."
+ - title: Создание Своих Коллекций
+ icon: building
+ url: "core/custom-collections.html"
+ by: Martin Odersky, Lex Spoon и Julien Richard-Foy
+ description: "В этом документе вы узнаете, как коллекции помогают вам реализовывать собственные персональные коллекции, используя всего несколько строчек кода и переиспользуя большую часть функциональности коллекций из базового фреймворка."
+ - title: Добавление своих операций к коллекциям
+ icon: building
+ url: "core/custom-collection-operations.html"
+ by: Julien Richard-Foy
+ description: "В данном руководстве показано, как написать операции, которые могут быть применены к любому типу коллекции и которые вернут исходный тип коллекции, а также как написать операции, которые можно параметризовать по типу коллекции."
+
+- category: Язык
+ description: "Руководства и обзоры, охватывающие функционал языка Scala."
+ overviews:
+ - title: Строковая интерполяция
+ icon: dollar-sign
+ url: "core/string-interpolation.html"
+ description: >
+ Строковая интерполяция позволяет пользователям встраивать данные из переменных непосредственно в обрабатываемые строковые литералы. Вот пример:
+
val name = "James"
+ println(s"Hello, $name") // Hello, James
+ В приведенном выше литерале s"Hello, $name" - это перерабатываемая строка. Такая запись указывает компилятору сделать некоторую дополнительную работу над самим литералом. Сам обрабатываемый строковый литерал обозначается набором символов, предшествующим ". Интерполяция строк была введена в SIP-11, который содержит все детали реализации.
+ - title: Неявные Классы
+ by: Josh Suereth
+ description: "В Скале 2.10 введена новая функциональность, называемая неявными классами. Неявный класс - это класс, помеченный ключевым словом implicit. Это ключевое слово позволяет использовать первичный конструктор класса в процессе неявного преобразования одного типа в другой, когда класс находится в области видимости."
+ url: "core/implicit-classes.html"
+ - title: Вычислительные Классы и Универсальные Трейты
+ by: Mark Harrah
+ description: "Вычислительные-Классы - это новый механизм в Scala, позволяющий избежать создания объектов во время исполнения, которое достигается за счет объявления класса в качестве подкласса AnyVal."
+ icon: gem
+ url: "core/value-classes.html"
+
+- category: Создание своих библиотек
+ description: "Руководства по вкладу в создание библиотек с открытым исходным кодом в Scala экосистеме"
+ overviews:
+ - title: Справочник для автора библиотек
+ by: "Julien Richard-Foy"
+ icon: tasks
+ url: "contributors/index.html"
+ description: "Список инструментов, которые авторы библиотек должны настроить для публикации и документирования своих библиотек."
+
+- category: Параллельное и Конкурентное Программирование
+ description: "Полное руководство по параллельному и конкурентному программированию в библиотеках Scala."
+ overviews:
+ - title: Futures и Promise
+ by: "Philipp Haller, Aleksandar Prokopec, Heather Miller, Viktor Klang, Roland Kuhn и Vojin Jovanovic"
+ icon: tasks
+ url: "core/futures.html"
+ description: "Фьючерсы (Futures) дают возможность эффективно и без блокировок осуществлять многие операции параллельно. Future - это обертка над объектом, который может пока ещё не существовать. Как правило, вычисление Future осуществляется конкурентно и может быть использовано позднее. Композиция таких конкурентных процессов приводит в итоге к более быстрому, асинхронному, не блокирующему, параллельно исполняемому коду."
+ - title: Параллельные коллекции
+ by: Aleksandar Prokopec и Heather Miller
+ icon: rocket
+ url: "parallel-collections/overview.html"
+ description: "Scala's Parallel Collections Library."
+ subdocs:
+ - title: Обзор
+ url: "parallel-collections/overview.html"
+ - title: Реализация Параллельных Коллекций
+ url: "parallel-collections/concrete-parallel-collections.html"
+ - title: Преобразования Параллельных Коллекций
+ url: "parallel-collections/conversions.html"
+ - title: Многопоточные Префиксные Деревья
+ url: "parallel-collections/ctries.html"
+ - title: Архитектура Библиотеки Параллельных Коллекций
+ url: "parallel-collections/architecture.html"
+ - title: Создание Пользовательской Параллельной Коллекции
+ url: "parallel-collections/custom-parallel-collections.html"
+ - title: Конфигурирование Параллельных Коллекций
+ url: "parallel-collections/configuration.html"
+ - title: Измерение производительности
+ url: "parallel-collections/performance.html"
+
+- category: Совместимость
+ description: "Что с чем работает (или не работает)."
+ overviews:
+ - title: Совместимость с версиями JDK
+ description: "Какие версии Scala работают с какими версиями JDK"
+ icon: coffee
+ url: "jdk-compatibility/overview.html"
+ - title: Совместимость релизов Scala на уровне двоичного кода
+ description: "Когда две версии Scala совместимы на уровне двоичного кода - это означает что проект безопасно компилировать на одной версии Scala и связывать с другой версией Scala во время исполнения. Безопасное связывание во время исполнения (только!) означает, что JVM не бросит исключение (подкласса) LinkageError при выполнении вашей программы в смешанном сценарии, предполагая, что никаких исключений не возникает при компиляции и запуске на одной и той же версии Scala. В том числе, это означает, что можно иметь внешние зависимости в программе, использующие другую версию Scala, чем та, с которой вы скомпилировали проект, до тех пор пока они совместимы на уровне двоичного кода. Другими словами, раздельная компиляция на разных но совместимых на уровне двоичного кода версиях не создает новых проблем, по сравнению с компиляцией и запуском проекта на одной и той же версии Scala."
+ icon: puzzle-piece
+ url: "core/binary-compatibility-of-scala-releases.html"
+ - title: Двоичная Совместимость для Авторов Библиотек
+ description: "Для любой продуктивной экосистемы важно иметь разнообразный и исчерпывающий набор библиотек. Хотя библиотеки Scala легко разрабатывать и распространять, хорошая разработка библиотек выходит за рамки простого написания кода и его публикации. В этом руководстве мы рассматриваем важную тему двоичной совместимости."
+ icon: puzzle-piece
+ url: "core/binary-compatibility-for-library-authors.html"
+
+- category: Инструменты
+ description: "Справочный материал по основным инструментам Scala, таким как Scala REPL и генерации Scaladoc."
+ overviews:
+ - title: Scala REPL
+ icon: terminal
+ url: "repl/overview.html"
+ description: |
+ Scala REPL это инструмент (scala) для обработки выражений в Scala.
+
+ Он выполняет исходный скрипт, который в начале оборачивает в специальный блок, который затем компилирует и запускает.
+ - title: Scaladoc
+ url: "scaladoc/overview.html"
+ icon: book
+ description: "Scala API инструмента генерации документации."
+ subdocs:
+ - title: Обзор
+ url: "scaladoc/overview.html"
+ - title: Scaladoc для Авторов Библиотек
+ url: "scaladoc/for-library-authors.html"
+ - title: Использование интерфейса Scaladoc
+ url: "scaladoc/interface.html"
+
+- category: Компилятор
+ description: "Руководства и обзоры, охватывающие компилятор Scala: плагины компилятора, рефлексия и инструменты метапрограммирования такие как макросы."
+ overviews:
+ - title: Рефлексия
+ by: Heather Miller, Eugene Burmako и Philipp Haller
+ icon: binoculars
+ url: "reflection/overview.html"
+ description: Фреймворк рефлексии в Scala.
+ label-text: experimental
+ subdocs:
+ - title: Overview
+ url: "reflection/overview.html"
+ - title: Environment, Universes, and Mirrors
+ url: "reflection/environment-universes-mirrors.html"
+ - title: Symbols, Trees, and Types
+ url: "reflection/symbols-trees-types.html"
+ - title: Annotations, Names, Scopes, and More
+ url: "reflection/annotations-names-scopes.html"
+ - title: TypeTags and Manifests
+ url: "reflection/typetags-manifests.html"
+ - title: Thread Safety
+ url: "reflection/thread-safety.html"
+ - title: Changes in Scala 2.11
+ url: "reflection/changelog211.html"
+ - title: Макросы
+ by: Eugene Burmako
+ icon: magic
+ url: "macros/usecases.html"
+ description: "Фреймворк метапрограммирования в Scala."
+ label-text: experimental
+ subdocs:
+ - title: Use Cases
+ url: "macros/usecases.html"
+ - title: Blackbox Vs Whitebox
+ url: "macros/blackbox-whitebox.html"
+ - title: Def Macros
+ url: "macros/overview.html"
+ - title: Quasiquotes
+ url: "quasiquotes/intro.html"
+ - title: Macro Bundles
+ url: "macros/bundles.html"
+ - title: Implicit Macros
+ url: "macros/implicits.html"
+ - title: Extractor Macros
+ url: "macros/extractors.html"
+ - title: Type Providers
+ url: "macros/typeproviders.html"
+ - title: Macro Annotations
+ url: "macros/annotations.html"
+ - title: Macro Paradise
+ url: "macros/paradise.html"
+ - title: Roadmap
+ url: "macros/roadmap.html"
+ - title: Changes in 2.11
+ url: "macros/changelog211.html"
+ - title: Quasiquotes
+ by: Denys Shabalin
+ icon: quote-left
+ url: "quasiquotes/setup.html"
+ description: "Quasiquotes наиболее подходящий способ манипулирования синтаксическим деревом Scala."
+ label-text: experimental
+ subdocs:
+ - title: Dependencies and setup
+ url: "quasiquotes/setup.html"
+ - title: Introduction
+ url: "quasiquotes/intro.html"
+ - title: Lifting
+ url: "quasiquotes/lifting.html"
+ - title: Unlifting
+ url: "quasiquotes/unlifting.html"
+ - title: Hygiene
+ url: "quasiquotes/hygiene.html"
+ - title: Use cases
+ url: "quasiquotes/usecases.html"
+ - title: Syntax summary
+ url: "quasiquotes/syntax-summary.html"
+ - title: Expression details
+ url: "quasiquotes/expression-details.html"
+ - title: Type details
+ url: "quasiquotes/type-details.html"
+ - title: Pattern details
+ url: "quasiquotes/pattern-details.html"
+ - title: Definition and import details
+ url: "quasiquotes/definition-details.html"
+ - title: Terminology summary
+ url: "quasiquotes/terminology.html"
+ - title: Future prospects
+ url: "quasiquotes/future.html"
+ - title: Плагины Компилятора
+ by: Lex Spoon и Seth Tisue
+ icon: puzzle-piece
+ url: "plugins/index.html"
+ description: "Используя плагины можно настраивать и расширять компилятор Scala. В этом руководстве описываются возможности плагина и рассказывается о том, как создать простой плагин."
+ - title: Опции Компилятора
+ by: Сообщество
+ icon: cog
+ url: "compiler-options/index.html"
+ description: "Различные варианты управления тем, как scalac компилирует код."
+
+
+- category: Наследие
+ description: "Руководство по функционалу, которые больше не соответствуют последним версиям Scala (2.12+)."
+ overviews:
+ - title: Scala коллекции с 2.8 по 2.12
+ by: Martin Odersky
+ icon: sitemap
+ url: "collections/introduction.html"
+ description: "Scala's Collection Library."
+ subdocs:
+ - title: Introduction
+ url: "collections/introduction.html"
+ - title: Mutable and Immutable Collections
+ url: "collections/overview.html"
+ - title: Trait Traversable
+ url: "collections/trait-traversable.html"
+ - title: Trait Iterable
+ url: "collections/trait-iterable.html"
+ - title: The sequence traits Seq, IndexedSeq, and LinearSeq
+ url: "collections/seqs.html"
+ - title: Sets
+ url: "collections/sets.html"
+ - title: Maps
+ url: "collections/maps.html"
+ - title: Concrete Immutable Collection Classes
+ url: "collections/concrete-immutable-collection-classes.html"
+ - title: Concrete Mutable Collection Classes
+ url: "collections/concrete-mutable-collection-classes.html"
+ - title: Arrays
+ url: "collections/arrays.html"
+ - title: Strings
+ url: "collections/strings.html"
+ - title: Performance Characteristics
+ url: "collections/performance-characteristics.html"
+ - title: Equality
+ url: "collections/equality.html"
+ - title: Views
+ url: "collections/views.html"
+ - title: Iterators
+ url: "collections/iterators.html"
+ - title: Creating Collections From Scratch
+ url: "collections/creating-collections-from-scratch.html"
+ - title: Conversions Between Java and Scala Collections
+ url: "collections/conversions-between-java-and-scala-collections.html"
+ - title: Migrating from Scala 2.7
+ url: "collections/migrating-from-scala-27.html"
+ - title: Архитектура Scala коллекций с 2.8 по 2.12
+ icon: building
+ url: "core/architecture-of-scala-collections.html"
+ by: Martin Odersky и Lex Spoon
+ description: "На этих страницах описывается архитектура фреймворка коллекций до версии 2.12 . По сравнению с API Коллекции вы узнаете здесь больше о внутренней работе фреймворка."
diff --git a/_data/overviews-uk.yml b/_data/overviews-uk.yml
new file mode 100644
index 0000000000..02be500922
--- /dev/null
+++ b/_data/overviews-uk.yml
@@ -0,0 +1,348 @@
+- category: Стандартна бібліотека
+ description: "Посібники та огляди стандартної бібліотеки Scala."
+ overviews:
+ - title: Scala колекції
+ by: Martin Odersky та Julien Richard-Foy
+ icon: sitemap
+ url: "collections-2.13/introduction.html"
+ description: "Бібліотека колекцій Scala."
+ subdocs:
+ - title: Вступ
+ url: "collections-2.13/introduction.html"
+ - title: Змінювані та незмінювані колекції
+ url: "collections-2.13/overview.html"
+ - title: Трейт Iterable
+ url: "collections-2.13/trait-iterable.html"
+ - title: Трейти послідовностей. Seq, IndexedSeq та LinearSeq
+ url: "collections-2.13/seqs.html"
+ - title: Реалізація незмінюваних колекцій
+ url: "collections-2.13/concrete-immutable-collection-classes.html"
+ - title: Реалізація змінюваних колекцій
+ url: "collections-2.13/concrete-mutable-collection-classes.html"
+ - title: Масиви
+ url: "collections-2.13/arrays.html"
+ - title: Рядки
+ url: "collections-2.13/strings.html"
+ - title: Показники продуктивності
+ url: "collections-2.13/performance-characteristics.html"
+ - title: Рівність
+ url: "collections-2.13/equality.html"
+ - title: Відображення
+ url: "collections-2.13/views.html"
+ - title: Ітератори
+ url: "collections-2.13/iterators.html"
+ - title: Створення колекцій з нуля
+ url: "collections-2.13/creating-collections-from-scratch.html"
+ - title: Перетворення між колекціями Java та Scala
+ url: "collections-2.13/conversions-between-java-and-scala-collections.html"
+ - title: Міграція проєкту до колекцій Scala 2.13
+ icon: sitemap
+ url: "core/collections-migration-213.html"
+ description: "Ця сторінка описує основні зміни в колекціях для користувачів, які переходять на Scala 2.13. Також, розглянуто варіанти побудови проєкти з перехресною сумісністю для Scala 2.11/2.12 і 2.13."
+ - title: Архітектура колекцій Scala
+ icon: sitemap
+ url: "core/architecture-of-scala-213-collections.html"
+ by: Julien Richard-Foy
+ description: "Ці сторінки описують архітектуру фреймворку колекцій, представленого в Scala 2.13. У порівнянні з Collections API ви дізнаєтеся більше про внутрішню роботу фреймворка."
+ - title: Реалізація користувацьких колекцій
+ icon: building
+ url: "core/custom-collections.html"
+ by: Martin Odersky, Lex Spoon та Julien Richard-Foy
+ description: "У цьому документі ви дізнаєтеся, як фреймворк колекцій допомагає вам визначати власні колекції за допомогою кількох рядків коду, повторно використовуючи переважну частину функцій колекції з фреймворку."
+ - title: Додавання спеціальних операцій до колекцій
+ icon: building
+ url: "core/custom-collection-operations.html"
+ by: Julien Richard-Foy
+ description: "У цьому посібнику показано, як писати перетворення, що застосовуються до всіх типів колекцій і повертати той самий тип колекції. Також, як писати операції, які параметризуються типом колекції."
+
+- category: Мова
+ description: "Посібники та огляди, що охоплюють функції на мові Scala."
+ overviews:
+ - title: Міграція зі Scala 2 на Scala 3
+ by: Adrien Piquerez
+ icon: suitcase
+ root: "scala3/guides/"
+ url: "migration/compatibility-intro.html"
+ description: "Все, що потрібно знати про сумісність і міграцію на Scala 3."
+ - title: Макроси Scala 3
+ by: Nicolas Stucki
+ icon: magic
+ root: "scala3/guides/"
+ url: "macros"
+ description: "Детальний підручник, який охоплює всі можливості, пов'язані з написанням макросів у Scala 3."
+ label-text: нове в Scala 3
+ - title: Класи значень та універсальні трейти
+ by: Mark Harrah
+ description: "Класи значень – це новий механізм у Scala, що дозволяє уникнути виділення об'єктів під час виконання. Це досягається за допомогою визначення нових підкласів AnyVal."
+ icon: gem
+ url: "core/value-classes.html"
+ - title: Огляд TASTy
+ by: Alvin Alexander
+ icon: birthday-cake
+ label-text: нове в Scala 3
+ root: "scala3/guides/"
+ url: "tasty-overview.html"
+ description: "Огляд формату TASTy, призначеного для користувачів мови Scala."
+ - title: Інтерполяція рядків
+ icon: dollar-sign
+ url: "core/string-interpolation.html"
+ description: >
+ Інтерполяція рядків дозволяє користувачам вбудовувати посилання на змінні безпосередньо в оброблені рядкові літерали. Ось приклад:
+
val name = "James"
+ println(s"Hello, $name") // Hello, James
+ Літерал s"Hello, $name" є рядковим літералом, який буде додатково оброблено. Це означає, що компілятор виконує додаткову роботу над цим літералом. Оброблений рядковий літерал позначається набором символів, що передують ". Інтерполяція рядків була введена в SIP-11.
+ - title: Неявні класи
+ by: Josh Suereth
+ description: "Scala 2.10 представила нову функцію під назвою неявні класи. Неявний клас — це клас, позначений ключовим словом implicit. Це ключове слово робить основний конструктор класу доступним для неявних перетворень, коли клас знаходиться в області видимості."
+ url: "core/implicit-classes.html"
+
+- category: Створення бібліотек
+ description: "Посібники щодо розробки бібліотек з відкритим кодом для екосистеми Scala."
+ overviews:
+ - title: Посібник для авторів бібліотек
+ by: Julien Richard-Foy
+ icon: tasks
+ url: "contributors/index.html"
+ description: "Перелічує всі інструменти, які автори бібліотек мають налаштувати для публікації та документування своїх бібліотек."
+
+- category: Паралельне та конкурентне програмування
+ description: "Повні посібники, що охоплюють деякі бібліотеки Scala для паралельного та конкурентного програмування."
+ overviews:
+ - title: Future та Promise
+ by: Philipp Haller, Aleksandar Prokopec, Heather Miller, Viktor Klang, Roland Kuhn та Vojin Jovanovic
+ icon: tasks
+ url: "core/futures.html"
+ description: "Ф'ючери дають можливість міркувати про паралельне виконання багатьох операцій – ефективним і не блокуючим способом. Ф'ючер — це об’єкт-заповнювач для значення, яке може ще не існувати. Як правило, вартість Ф'ючеру надається одночасно і може згодом використовуватися. Складання одночасних завдань таким чином, як правило, призводить до швидшого, асинхронного, не блокувального паралельного коду."
+ - title: Паралельні колекції
+ by: Aleksandar Prokopec та Heather Miller
+ icon: rocket
+ url: "parallel-collections/overview.html"
+ description: "Бібліотека паралельних колекцій Scala."
+ subdocs:
+ - title: Огляд
+ url: "parallel-collections/overview.html"
+ - title: Реалізація паралельних колекцій
+ url: "parallel-collections/concrete-parallel-collections.html"
+ - title: Перетворення паралельних колекцій
+ url: "parallel-collections/conversions.html"
+ - title: Конкурентні Try
+ url: "parallel-collections/ctries.html"
+ - title: Архітектура бібліотеки паралельних колекцій
+ url: "parallel-collections/architecture.html"
+ - title: Створення користувацьких паралельних колекцій
+ url: "parallel-collections/custom-parallel-collections.html"
+ - title: Конфігурація паралельних колекцій
+ url: "parallel-collections/configuration.html"
+ - title: Вимірювання продуктивності
+ url: "parallel-collections/performance.html"
+
+- category: Сумісність
+ description: "Що з чим працює (чи ні)."
+ overviews:
+ - title: Сумісність версій JDK
+ description: "Які версії Scala працюють на яких версіях JDK"
+ icon: coffee
+ url: "jdk-compatibility/overview.html"
+ - title: Бінарна сумісність релізів Scala
+ description: "Якщо дві версії Scala бінарно сумісні, можна безпечно скомпілювати свій проєкт на одній версії Scala та зв'язати з іншою версією Scala під час виконання. Безпечне зв'язування під час виконання (тільки!) означає, що JVM не генерує (підклас) LinkageError під час виконання вашої програми у змішаному сценарії, припускаючи, що вона не виникає при компіляції та запуску в одній версії Scala. Конкретно це означає, що ви можете мати зовнішні залежності від вашого шляху до класу під час виконання, які використовують іншу версію Scala, ніж та, з якою ви компілюєте, за умови, що вони сумісні з бінарними файлами. Іншими словами, окрема компіляція в різних версіях, сумісних з бінарними файлами, не створює проблем у порівнянні з компіляцією та запуском всього в одній версії Scala."
+ icon: puzzle-piece
+ url: "core/binary-compatibility-of-scala-releases.html"
+ - title: Бінарна сумісність для авторів бібліотек
+ description: "Різноманітний і повний набір бібліотек важливий для будь-якої продуктивної екосистеми програмного забезпечення. Хоча розробляти та розповсюджувати бібліотеки Scala легко, добре авторство бібліотеки виходить за рамки простого написання коду та його публікації. У цьому посібнику ми розглянемо важливу тему бінарної сумісності."
+ icon: puzzle-piece
+ url: "core/binary-compatibility-for-library-authors.html"
+
+- category: Інструменти
+ description: "Довідковий матеріал про основні інструменти Scala, такі як покоління Scala REPL і Scaladoc."
+ overviews:
+ - title: Scala 2 REPL
+ icon: terminal
+ url: "repl/overview.html"
+ description: |
+ Scala REPL це інструмент (scala) для виконання виразів в Scala.
+
+ Команда scala виконає скрипт шляхом обгортання його в шаблон, а потім компіляції та виконання отриманої програми
+ - title: Scaladoc для Scala 3
+ by: Krzysztof Romanowski, Aleksander Boruch-Gruszecki, Andrzej Ratajczak, Kacper Korban, Filip Zybała
+ icon: book
+ root: "scala3/guides/"
+ url: "scaladoc"
+ label-text: оновлено
+ description: "Оновлення в Scala 3 для інструменту генерації документації API."
+ - title: Scaladoc
+ url: "scaladoc/overview.html"
+ icon: book
+ description: "Інструмент Scala для генерації документації для API."
+ subdocs:
+ - title: Огляд
+ url: "scaladoc/overview.html"
+ - title: Scaladoc для авторів бібліотек
+ url: "scaladoc/for-library-authors.html"
+ - title: Використання інтерфейсу Scaladoc
+ url: "scaladoc/interface.html"
+
+- category: Компілятор
+ description: "Посібники та огляди компілятора Scala: плагіни компілятора, інструменти рефлексії та метапрограмування, такі як макроси."
+ overviews:
+ - title: "Посібник з внесення змін у Scala 3"
+ by: Jamie Thompson, Anatolii Kmetiuk
+ icon: cogs
+ root: "scala3/guides/"
+ url: "contribution/contribution-intro.html"
+ description: "Посібник з компілятора Scala 3 та вирішення проблем."
+ - title: Рефлексія в Scala 2
+ by: Heather Miller, Eugene Burmako та Philipp Haller
+ icon: binoculars
+ url: "reflection/overview.html"
+ description: Фреймворк Scala для рефлексії під час виконання/компіляції.
+ label-text: відсутнє в Scala 3
+ subdocs:
+ - title: Огляд
+ url: "reflection/overview.html"
+ - title: Environment, Universe та Mirror
+ url: "reflection/environment-universes-mirrors.html"
+ - title: Symbol, Tree та Type
+ url: "reflection/symbols-trees-types.html"
+ - title: Annotation, Name, Scope та More
+ url: "reflection/annotations-names-scopes.html"
+ - title: TypeTag та Manifest
+ url: "reflection/typetags-manifests.html"
+ - title: Безпека потоків
+ url: "reflection/thread-safety.html"
+ - title: Зміни в Scala 2.11
+ url: "reflection/changelog211.html"
+ - title: Макроси в Scala 2
+ by: Eugene Burmako
+ icon: magic
+ url: "macros/usecases.html"
+ description: "Фреймворк метапрограмування Scala."
+ label-text: відсутнє в Scala 3
+ subdocs:
+ - title: Випадки використання
+ url: "macros/usecases.html"
+ - title: Blackbox проти Whitebox
+ url: "macros/blackbox-whitebox.html"
+ - title: Макроси Def
+ url: "macros/overview.html"
+ - title: Квазіцитати
+ url: "quasiquotes/intro.html"
+ - title: Пакети макросів
+ url: "macros/bundles.html"
+ - title: Неявні макроси
+ url: "macros/implicits.html"
+ - title: Макроси-екстрактори
+ url: "macros/extractors.html"
+ - title: Провайдери типів
+ url: "macros/typeproviders.html"
+ - title: Анотації макросів
+ url: "macros/annotations.html"
+ - title: Макрос Paradise
+ url: "macros/paradise.html"
+ - title: Дорожня карта
+ url: "macros/roadmap.html"
+ - title: Зміни в 2.11
+ url: "macros/changelog211.html"
+ - title: Квазіцитати в Scala 2
+ by: Denys Shabalin
+ icon: quote-left
+ url: "quasiquotes/setup.html"
+ description: "Квазіцитати — це зручний спосіб маніпулювати синтаксичними деревами Scala."
+ label-text: відсутнє в Scala 3
+ subdocs:
+ - title: Залежності та налаштування
+ url: "quasiquotes/setup.html"
+ - title: Вступ
+ url: "quasiquotes/intro.html"
+ - title: Підіймання
+ url: "quasiquotes/lifting.html"
+ - title: Опускання
+ url: "quasiquotes/unlifting.html"
+ - title: Гігієна
+ url: "quasiquotes/hygiene.html"
+ - title: Випадки використання
+ url: "quasiquotes/usecases.html"
+ - title: Резюме синтаксису
+ url: "quasiquotes/syntax-summary.html"
+ - title: Деталі виразів
+ url: "quasiquotes/expression-details.html"
+ - title: Деталі типів
+ url: "quasiquotes/type-details.html"
+ - title: Деталі патернів
+ url: "quasiquotes/pattern-details.html"
+ - title: Деталі визначення та імпорту
+ url: "quasiquotes/definition-details.html"
+ - title: Резюме термінології
+ url: "quasiquotes/terminology.html"
+ - title: Майбутні перспективи
+ url: "quasiquotes/future.html"
+ - title: Плагіни компілятора
+ by: Lex Spoon та Seth Tisue
+ icon: puzzle-piece
+ url: "plugins/index.html"
+ description: "Плагіни компілятора дозволяють налаштовувати та розширювати компілятор Scala. У цьому підручнику описується функція плагіну та пояснюється, як створити простий плагін."
+ - title: Параметри компілятора
+ by: Community
+ icon: cog
+ url: "compiler-options/index.html"
+ description: "Різні параметри того як scalac компілює ваш код."
+ - title: Форматування помилок
+ by: Torsten Schmits
+ icon: cog
+ url: "compiler-options/errors.html"
+ description: "Новий механізм для більш зручних повідомлень про помилки, друку ланцюжків залежних неявних параметрів та кольорових відмінностей знайдених/потрібних типів."
+ - title: Оптимізатор
+ by: Lukas Rytz та Andrew Marki
+ icon: cog
+ url: "compiler-options/optimizer.html"
+ description: "Компілятор може виконувати різні оптимізації."
+
+- category: Спадщина (legacy)
+ description: "Посібники, що охоплюють функції, які більше не стосуються останніх версій Scala (2.12+)."
+ overviews:
+ - title: Колекції Scala з 2.8 до 2.12
+ by: Martin Odersky
+ icon: sitemap
+ url: "collections/introduction.html"
+ description: "Бібліотека колекцій Scala."
+ subdocs:
+ - title: Вступ
+ url: "collections/introduction.html"
+ - title: Змінювані та незмінювані колекції
+ url: "collections/overview.html"
+ - title: Трейт Traversable
+ url: "collections/trait-traversable.html"
+ - title: Трейт Iterable
+ url: "collections/trait-iterable.html"
+ - title: Трейти послідовностей. Seq, IndexedSeq та LinearSeq
+ url: "collections/seqs.html"
+ - title: Множини
+ url: "collections/sets.html"
+ - title: Асоціативні масиви
+ url: "collections/maps.html"
+ - title: Реалізація незмінюваних колекцій
+ url: "collections/concrete-immutable-collection-classes.html"
+ - title: Реалізація змінюваних колекцій
+ url: "collections/concrete-mutable-collection-classes.html"
+ - title: Масиви
+ url: "collections/arrays.html"
+ - title: Рядки
+ url: "collections/strings.html"
+ - title: Показники продуктивності
+ url: "collections/performance-characteristics.html"
+ - title: Рівність
+ url: "collections/equality.html"
+ - title: Відображення
+ url: "collections/views.html"
+ - title: Ітератори
+ url: "collections/iterators.html"
+ - title: Створення колекцій з нуля
+ url: "collections/creating-collections-from-scratch.html"
+ - title: Перетворення між колекціями Java та Scala
+ url: "collections/conversions-between-java-and-scala-collections.html"
+ - title: Міграція з версії Scala 2.7
+ url: "collections/migrating-from-scala-27.html"
+ - title: Архітектура колекцій Scala з 2.8 до 2.12
+ icon: building
+ url: "core/architecture-of-scala-collections.html"
+ by: Martin Odersky та Lex Spoon
+ description: "На цих сторінках детально описується архітектура фреймворку колекцій Scala. У порівнянні з Collections API ви дізнаєтеся більше про внутрішню роботу фреймворку. Ви також дізнаєтеся, як ця архітектура допомагає вам визначати власні колекції за допомогою кількох рядків коду, повторно використовуючи переважну частину функцій колекції з фреймворку."
diff --git a/_data/overviews-zh-cn.yml b/_data/overviews-zh-cn.yml
new file mode 100644
index 0000000000..1c48218eef
--- /dev/null
+++ b/_data/overviews-zh-cn.yml
@@ -0,0 +1,312 @@
+- category: 标准库
+ description: "涵盖 Scala 标准库的参考与概览"
+ overviews:
+ - title: Scala 容器
+ by: Martin Odersky and Julien Richard-Foy
+ icon: sitemap
+ url: "collections-2.13/introduction.html"
+ description: "Scala 的容器库"
+ subdocs:
+ - title: 简介
+ url: "collections-2.13/introduction.html"
+ - title: 可变与不可变容器
+ url: "collections-2.13/overview.html"
+ - title: Iterable 特质
+ url: "collections-2.13/trait-iterable.html"
+ - title: 序列特质 Seq, IndexedSeq, 和 LinearSeq
+ url: "collections-2.13/seqs.html"
+ - title: 具体不可变容器类
+ url: "collections-2.13/concrete-immutable-collection-classes.html"
+ - title: 具体可变容器类
+ url: "collections-2.13/concrete-mutable-collection-classes.html"
+ - title: 数组
+ url: "collections-2.13/arrays.html"
+ - title: 字符串
+ url: "collections-2.13/strings.html"
+ - title: 性能特点
+ url: "collections-2.13/performance-characteristics.html"
+ - title: 相等性
+ url: "collections-2.13/equality.html"
+ - title: 视图
+ url: "collections-2.13/views.html"
+ - title: 迭代器
+ url: "collections-2.13/iterators.html"
+ - title: 从头开始创建容器
+ url: "collections-2.13/creating-collections-from-scratch.html"
+ - title: Java 与 Scala 间的容器转换
+ url: "collections-2.13/conversions-between-java-and-scala-collections.html"
+ - title: 迁移项目容器至 Scala 2.13 的容器
+ icon: sitemap
+ url: "core/collections-migration-213.html"
+ description: "本篇向欲迁移至 Scala 2.13 的容器用户介绍了主要变更并展示了如何通过 Scala 2.11,2.12 和 2.13 进行交叉编译"
+ - title: Scala 容器架构
+ icon: sitemap
+ url: "core/architecture-of-scala-213-collections.html"
+ by: Julien Richard-Foy
+ description: "这几篇介绍了引进到 Scala 2.13 中的容器框架的架构,对照容器API就能知晓更多框架内部工作机制"
+ - title: 实现定制容器
+ icon: building
+ url: "core/custom-collections.html"
+ by: Martin Odersky, Lex Spoon and Julien Richard-Foy
+ description: "从本篇中你会了解到如何利用容器框架通过几行代码来定义自己的容器,来重用来自框架的绝大部分容器功能。"
+ - title: 新增定制的容器操作
+ icon: building
+ url: "core/custom-collection-operations.html"
+ by: Julien Richard-Foy
+ description: "本篇展示了如何定制可应用于任意容器类型并返回相同类型的操作,以及如何定制带有欲编译容器类型参数的操作"
+
+- category: 语言
+ description: "涵盖 Scala 语言特性的参考与概览"
+ overviews:
+ - title: 字符串内插
+ icon: dollar-sign
+ url: "core/string-interpolation.html"
+ description: >
+ 字符串内插允许用户在字符串字面插值中直接嵌入变量引用。这里有个例子:
+ String Interpolation allows users to embed variable references directly in processed string literals. Here’s an example:
+
val name = "James"
+ println(s"Hello, $name") // Hello, James
+ scala 命令会通过包装源脚本到一模板中来执行它,然后编译并执行结果程序
+ - title: Scaladoc
+ url: "scaladoc/overview.html"
+ icon: book
+ description: "Scala 的 API 文档生成工具"
+ subdocs:
+ - title: 概览
+ url: "scaladoc/overview.html"
+ - title: 针对库作者的 Scaladoc
+ url: "scaladoc/for-library-authors.html"
+ - title: 使用 Scaladoc 接口
+ url: "scaladoc/interface.html"
+
+- category: 编译器
+ description: "涵盖 Scala 编译器的参考和概览:编译器插件,反射,以及元编程工具比如宏"
+ overviews:
+ - title: 反射
+ by: Heather Miller, Eugene Burmako, and Philipp Haller
+ icon: binoculars
+ url: "reflection/overview.html"
+ description: Scala 的运行时和编译期的反射框架
+ label-text: 实验
+ subdocs:
+ - title: 概览
+ url: "reflection/overview.html"
+ - title: 环境,通用和镜像(Environment, Universes, and Mirrors)
+ url: "reflection/environment-universes-mirrors.html"
+ - title: 符号,树和类型(Symbols, Trees, and Types)
+ url: "reflection/symbols-trees-types.html"
+ - title: 标号,名称,作用域及其他(Annotations, Names, Scopes, and More)
+ url: "reflection/annotations-names-scopes.html"
+ - title: TypeTags 和 Manifests
+ url: "reflection/typetags-manifests.html"
+ - title: 线程安全
+ url: "reflection/thread-safety.html"
+ - title: Scala 2.11 中的变化
+ url: "reflection/changelog211.html"
+ - title: 宏
+ by: Eugene Burmako
+ icon: magic
+ url: "macros/usecases.html"
+ description: "Scala 的元编程框架"
+ label-text: 实验
+ subdocs:
+ - title: 用例
+ url: "macros/usecases.html"
+ - title: 黑盒与白盒
+ url: "macros/blackbox-whitebox.html"
+ - title: Def 宏
+ url: "macros/overview.html"
+ - title: 拟引号(Quasiquotes)
+ url: "quasiquotes/intro.html"
+ - title: 宏绑定
+ url: "macros/bundles.html"
+ - title: 隐式宏
+ url: "macros/implicits.html"
+ - title: Extractor 宏
+ url: "macros/extractors.html"
+ - title: 类型 Providers
+ url: "macros/typeproviders.html"
+ - title: 宏标号
+ url: "macros/annotations.html"
+ - title: 宏乐园
+ url: "macros/paradise.html"
+ - title: 路线图
+ url: "macros/roadmap.html"
+ - title: 2.11 中的变化
+ url: "macros/changelog211.html"
+ - title: 拟引号
+ by: Denys Shabalin
+ icon: quote-left
+ url: "quasiquotes/setup.html"
+ description: "拟引号是操作 Scala 语法树的便捷方式"
+ label-text: 实验
+ subdocs:
+ - title: 依赖和设置
+ url: "quasiquotes/setup.html"
+ - title: 简介
+ url: "quasiquotes/intro.html"
+ - title: 提升(Lifting)
+ url: "quasiquotes/lifting.html"
+ - title: 拉降(Unlifting)
+ url: "quasiquotes/unlifting.html"
+ - title: 卫生(Hygiene)
+ url: "quasiquotes/hygiene.html"
+ - title: 用例
+ url: "quasiquotes/usecases.html"
+ - title: 语法总结
+ url: "quasiquotes/syntax-summary.html"
+ - title: 表达式细节
+ url: "quasiquotes/expression-details.html"
+ - title: 类型细节
+ url: "quasiquotes/type-details.html"
+ - title: 模式细节
+ url: "quasiquotes/pattern-details.html"
+ - title: 定义和引用细节
+ url: "quasiquotes/definition-details.html"
+ - title: 属于总结
+ url: "quasiquotes/terminology.html"
+ - title: 未来展望
+ url: "quasiquotes/future.html"
+ - title: 编译器插件
+ by: Lex Spoon and Seth Tisue
+ icon: puzzle-piece
+ url: "plugins/index.html"
+ description: "编译器插件允许定制和扩展 Scala 编译器。本篇导引描述了插件设施并带你领略如何创作一个简单插件"
+ - title: 编译器选项
+ by: Community
+ icon: cog
+ url: "compiler-options/index.html"
+ description: "控制 scalac 如何编译代码的各种选项"
+ - title: 错误格式
+ by: Torsten Schmits
+ icon: cog
+ url: "compiler-options/errors.html"
+ description: "一个新的用户友好的错误消息引擎,可以打印依赖的隐式链,颜色区分找到的和所需的类型差异"
+
+
+- category: 遗留问题
+ description: "涵盖一些与最近的 Scala 版本(2.12+)不再相关的特性的参考"
+ overviews:
+ - title: Scala 2.8 到 2.12 的容器
+ by: Martin Odersky
+ icon: sitemap
+ url: "collections/introduction.html"
+ description: "Scala 的容器库"
+ subdocs:
+ - title: 简介
+ url: "collections/introduction.html"
+ - title: 可变和不可变容器
+ url: "collections/overview.html"
+ - title: Traversable 特质
+ url: "collections/trait-traversable.html"
+ - title: Iterable 特质
+ url: "collections/trait-iterable.html"
+ - title: 序列特质 Seq, IndexedSeq, 和 LinearSeq
+ url: "collections/seqs.html"
+ - title: 集合(Sets)
+ url: "collections/sets.html"
+ - title: 映射(Maps)
+ url: "collections/maps.html"
+ - title: 具体的不可变容器类
+ url: "collections/concrete-immutable-collection-classes.html"
+ - title: 具体的可变容器类
+ url: "collections/concrete-mutable-collection-classes.html"
+ - title: 数组
+ url: "collections/arrays.html"
+ - title: 字符串
+ url: "collections/strings.html"
+ - title: 性能特点
+ url: "collections/performance-characteristics.html"
+ - title: 相等性
+ url: "collections/equality.html"
+ - title: 视图
+ url: "collections/views.html"
+ - title: 迭代器
+ url: "collections/iterators.html"
+ - title: 从头开始创建容器
+ url: "collections/creating-collections-from-scratch.html"
+ - title: Java 和 Scala 间容器转换
+ url: "collections/conversions-between-java-and-scala-collections.html"
+ - title: 从 Scala 2.7 迁移
+ url: "collections/migrating-from-scala-27.html"
+ - title: Scala 2.8 到 2.12 的容器架构
+ icon: building
+ url: "core/architecture-of-scala-collections.html"
+ by: Martin Odersky and Lex Spoon
+ description: "本篇细致地描述了 Scala 容器框架的架构,对比容器 API 你会发现更多框架的内部工作机制。你也会学到该架构如何帮你通过几行代码定义自己的容器,来重用来自框架的绝大部分容器功能。"
diff --git a/_data/overviews.yml b/_data/overviews.yml
index 784d7291e3..5756db5e3e 100644
--- a/_data/overviews.yml
+++ b/_data/overviews.yml
@@ -1,63 +1,91 @@
-
- category: Standard Library
description: "Guides and overviews covering the Scala standard library."
overviews:
- - title: Collections
- by: Martin Odersky
+ - title: Scala Collections
+ by: Martin Odersky and Julien Richard-Foy
icon: sitemap
- url: "collections/introduction.html"
+ url: "collections-2.13/introduction.html"
description: "Scala's Collection Library."
subdocs:
- title: Introduction
- url: "collections/introduction.html"
+ url: "collections-2.13/introduction.html"
- title: Mutable and Immutable Collections
- url: "collections/overview.html"
- - title: Trait Traversable
- url: "collections/trait-traversable.html"
+ url: "collections-2.13/overview.html"
- title: Trait Iterable
- url: "collections/trait-iterable.html"
+ url: "collections-2.13/trait-iterable.html"
- title: The sequence traits Seq, IndexedSeq, and LinearSeq
+ url: "collections-2.13/seqs.html"
- title: Concrete Immutable Collection Classes
- url: "collections/concrete-immutable-collection-classes.html"
+ url: "collections-2.13/concrete-immutable-collection-classes.html"
- title: Concrete Mutable Collection Classes
- url: "collections/concrete-mutable-collection-classes.html"
+ url: "collections-2.13/concrete-mutable-collection-classes.html"
- title: Arrays
- url: "collections/arrays.html"
+ url: "collections-2.13/arrays.html"
- title: Strings
- url: "collections/strings.html"
+ url: "collections-2.13/strings.html"
- title: Performance Characteristics
- url: "collections/performance-characteristics.html"
+ url: "collections-2.13/performance-characteristics.html"
- title: Equality
- url: "collections/equality.html"
+ url: "collections-2.13/equality.html"
- title: Views
- url: "collections/views.html"
+ url: "collections-2.13/views.html"
- title: Iterators
- url: "collections/iterators.html"
+ url: "collections-2.13/iterators.html"
- title: Creating Collections From Scratch
- url: "collections/creating-collections-from-scratch.html"
+ url: "collections-2.13/creating-collections-from-scratch.html"
- title: Conversions Between Java and Scala Collections
- url: "collections/conversions-between-java-and-scala-collections.html"
+ url: "collections-2.13/conversions-between-java-and-scala-collections.html"
+ - title: Migrating a Project to Scala 2.13's Collections
+ icon: sitemap
+ url: "core/collections-migration-213.html"
+ description: "This page describes the main changes for collection users that migrate to Scala
+ 2.13 and shows how to cross-build projects with Scala 2.11 / 2.12 and 2.13."
- title: The Architecture of Scala Collections
- icon: building
- url: "core/architecture-of-scala-collections.html"
- by: Martin Odersky and Lex Spoon
- description: "These pages describe the architecture of the Scala collections framework in detail. Compared to the Collections API you will find out more about the internal workings of the framework. You will also learn how this architecture helps you define your own collections in a few lines of code, while reusing the overwhelming part of collection functionality from the framework."
- - title: The Architecture of Scala 2.13’s Collections
icon: sitemap
url: "core/architecture-of-scala-213-collections.html"
by: Julien Richard-Foy
description: "These pages describe the architecture of the collections framework introduced in Scala 2.13. Compared to the Collections API you will find out more about the internal workings of the framework."
- - title: Custom Collection Types
+ - title: Implementing Custom Collections
icon: building
url: "core/custom-collections.html"
by: Martin Odersky, Lex Spoon and Julien Richard-Foy
description: "In this document you will learn how the collections framework helps you define your own collections in a few lines of code, while reusing the overwhelming part of collection functionality from the framework."
+ - title: Adding Custom Collection Operations
+ icon: building
+ url: "core/custom-collection-operations.html"
+ by: Julien Richard-Foy
+ description: "This guide shows how to write operations that can be applied to any collection type and return the same collection type, and how to write operations that can be parameterized by the type of collection to build."
- category: Language
description: "Guides and overviews covering features in the Scala language."
overviews:
+ - title: "Migration from Scala 2 to Scala 3"
+ by: Adrien Piquerez
+ icon: suitcase
+ root: "scala3/guides/"
+ url: "migration/compatibility-intro.html"
+ description: "Everything you need to know about compatibility and migration to Scala 3."
+ - title: Scala 3 Macros
+ by: Nicolas Stucki
+ icon: magic
+ root: "scala3/guides/"
+ url: "macros"
+ description: "A detailed tutorial to cover all the features involved in writing macros in Scala 3."
+ label-text: new in Scala 3
+ - title: Value Classes and Universal Traits
+ by: Mark Harrah
+ description: "Value classes are a new mechanism in Scala to avoid allocating runtime objects. This is accomplished through the definition of new AnyVal subclasses."
+ icon: gem
+ url: "core/value-classes.html"
+ - title: An Overview of TASTy
+ by: Alvin Alexander
+ icon: birthday-cake
+ label-text: new in Scala 3
+ root: "scala3/guides/"
+ url: "tasty-overview.html"
+ description: "An overview over the TASTy format aimed at end-users of the Scala language."
- title: String Interpolation
- icon: usd
+ icon: dollar-sign
url: "core/string-interpolation.html"
description: >
String Interpolation allows users to embed variable references directly in processed string literals. Here’s an example:
@@ -68,11 +96,24 @@
by: Josh Suereth
description: "Scala 2.10 introduced a new feature called implicit classes. An implicit class is a class marked with the implicit keyword. This keyword makes the class’ primary constructor available for implicit conversions when the class is in scope."
url: "core/implicit-classes.html"
- - title: Value Classes and Universal Traits
- by: Mark Harrah
- description: "Value classes are a new mechanism in Scala to avoid allocating runtime objects. This is accomplished through the definition of new AnyVal subclasses."
- icon: diamond
- url: "core/value-classes.html"
+ - title: The Scala Book
+ by: Alvin Alexander
+ icon: book
+ label-color: "#899295"
+ label-text: archived
+ url: "scala-book/introduction.html"
+ description: >
+ A light introduction to the Scala language, focused on Scala 2.
+ Now updated for Scala 3, we are in the process of merging the two.
+
+- category: Authoring Libraries
+ description: "Guides for contributing open source libraries to the Scala ecosystem."
+ overviews:
+ - title: Library Author Guide
+ by: "Julien Richard-Foy"
+ icon: tasks
+ url: "contributors/index.html"
+ description: "Lists all the tools that library authors should setup to publish and document their libraries."
- category: Parallel and Concurrent Programming
description: "Complete guides covering some of Scala's libraries for parallel and concurrent programming."
@@ -120,17 +161,27 @@
description: "A diverse and comprehensive set of libraries is important to any productive software ecosystem. While it is easy to develop and distribute Scala libraries, good library authorship goes beyond just writing code and publishing it. In this guide, we cover the important topic of Binary Compatibility."
icon: puzzle-piece
url: "core/binary-compatibility-for-library-authors.html"
+ - title: Nightly Versions of Scala
+ description: "We regularly publish 'nightlies' of both Scala 3 and Scala 2 so that users can preview and test the contents of upcoming releases. Here's how to find and use these versions."
+ url: "core/nightlies.html"
- category: "Tools"
description: "Reference material on core Scala tools like the Scala REPL and Scaladoc generation."
overviews:
- - title: Scala REPL
+ - title: Scala 2 REPL
icon: terminal
url: "repl/overview.html"
description: |
The Scala REPL is a tool (scala) for evaluating expressions in Scala.
The scala command will execute a source script by wrapping it in a template and then compiling and executing the resulting program
+ - title: Scaladoc For Scala 3
+ by: Krzysztof Romanowski, Aleksander Boruch-Gruszecki, Andrzej Ratajczak, Kacper Korban, Filip Zybała
+ icon: book
+ root: "scala3/guides/"
+ url: "scaladoc"
+ description: "Updates in Scala 3 to Scala’s API documentation generation tool."
+ label-text: updated
- title: Scaladoc
url: "scaladoc/overview.html"
icon: book
@@ -146,12 +197,12 @@
- category: Compiler
description: "Guides and overviews covering the Scala compiler: compiler plugins, reflection, and metaprogramming tools such as macros."
overviews:
- - title: Reflection
+ - title: Scala 2 Reflection
by: Heather Miller, Eugene Burmako, and Philipp Haller
icon: binoculars
url: "reflection/overview.html"
description: Scala's runtime/compile-time reflection framework.
- label-text: experimental
+ label-text: removed in Scala 3
subdocs:
- title: Overview
url: "reflection/overview.html"
@@ -167,12 +218,12 @@
url: "reflection/thread-safety.html"
- title: Changes in Scala 2.11
url: "reflection/changelog211.html"
- - title: Macros
+ - title: Scala 2 Macros
by: Eugene Burmako
icon: magic
url: "macros/usecases.html"
description: "Scala's metaprogramming framework."
- label-text: experimental
+ label-text: removed in Scala 3
subdocs:
- title: Use Cases
url: "macros/usecases.html"
@@ -198,12 +249,12 @@
url: "macros/roadmap.html"
- title: Changes in 2.11
url: "macros/changelog211.html"
- - title: Quasiquotes
+ - title: Quasiquotes in Scala 2
by: Denys Shabalin
icon: quote-left
url: "quasiquotes/setup.html"
description: "Quasiquotes are a convenient way to manipulate Scala syntax trees."
- label-text: experimental
+ label-text: removed in Scala 3
subdocs:
- title: Dependencies and setup
url: "quasiquotes/setup.html"
@@ -231,30 +282,74 @@
url: "quasiquotes/terminology.html"
- title: Future prospects
url: "quasiquotes/future.html"
- - title: Compiler Plugins
+ - title: Scala 2 Compiler Plugins
by: Lex Spoon and Seth Tisue
icon: puzzle-piece
url: "plugins/index.html"
description: "Compiler plugins permit customizing and extending the Scala compiler. This tutorial describes the plugin facility and walks you through how to create a simple plugin."
- - title: Compiler Options
+ - title: Scala 2 Compiler Options
by: Community
icon: cog
url: "compiler-options/index.html"
description: "Various options to control how scalac compiles your code."
-
+ - title: Error Formatting
+ by: Torsten Schmits
+ icon: cog
+ url: "compiler-options/errors.html"
+ description: "A new engine for more user-friendly error messages, printing chains of dependent implicits and colored found/required type diffs."
+ - title: Optimizer
+ by: Lukas Rytz and Andrew Marki
+ icon: cog
+ url: "compiler-options/optimizer.html"
+ description: "The compiler can perform various optimizations."
- category: Legacy
- description: "Guides covering features no longer relevant to recent Scala versions (2.11+)."
+ description: "Guides covering features no longer relevant to recent Scala versions (2.12+)."
overviews:
- - title: The Scala Actors Migration Guide
- by: Vojin Jovanovic and Philipp Haller
- icon: truck
- url: "core/actors-migration-guide.html"
- description: "To ease the migration from Scala Actors to Akka we have provided the Actor Migration Kit (AMK). The AMK consists of an extension to Scala Actors which is enabled by including the scala-actors-migration.jar on a project’s classpath. In addition, Akka 2.1 includes features, such as the ActorDSL singleton, which enable a simpler conversion of code using Scala Actors to Akka. The purpose of this document is to guide users through the migration process and explain how to use the AMK."
- - title: The Scala Actors API
- by: Philipp Haller and Stephen Tu
- icon: users
- url: "core/actors.html"
- description: "This guide describes the API of the scala.actors package of Scala 2.8/2.9. The organization follows groups of types that logically belong together. The trait hierarchy is taken into account to structure the individual sections. The focus is on the run-time behavior of the various methods that these traits define, thereby complementing the existing Scaladoc-based API documentation."
- label-color: "#899295"
- label-text: deprecated
+ - title: Scala 2.8 to 2.12’s Collections
+ by: Martin Odersky
+ icon: sitemap
+ url: "collections/introduction.html"
+ description: "Scala's Collection Library."
+ subdocs:
+ - title: Introduction
+ url: "collections/introduction.html"
+ - title: Mutable and Immutable Collections
+ url: "collections/overview.html"
+ - title: Trait Traversable
+ url: "collections/trait-traversable.html"
+ - title: Trait Iterable
+ url: "collections/trait-iterable.html"
+ - title: The sequence traits Seq, IndexedSeq, and LinearSeq
+ url: "collections/seqs.html"
+ - title: Sets
+ url: "collections/sets.html"
+ - title: Maps
+ url: "collections/maps.html"
+ - title: Concrete Immutable Collection Classes
+ url: "collections/concrete-immutable-collection-classes.html"
+ - title: Concrete Mutable Collection Classes
+ url: "collections/concrete-mutable-collection-classes.html"
+ - title: Arrays
+ url: "collections/arrays.html"
+ - title: Strings
+ url: "collections/strings.html"
+ - title: Performance Characteristics
+ url: "collections/performance-characteristics.html"
+ - title: Equality
+ url: "collections/equality.html"
+ - title: Views
+ url: "collections/views.html"
+ - title: Iterators
+ url: "collections/iterators.html"
+ - title: Creating Collections From Scratch
+ url: "collections/creating-collections-from-scratch.html"
+ - title: Conversions Between Java and Scala Collections
+ url: "collections/conversions-between-java-and-scala-collections.html"
+ - title: Migrating from Scala 2.7
+ url: "collections/migrating-from-scala-27.html"
+ - title: The Architecture of Scala 2.8 to 2.12’s Collections
+ icon: building
+ url: "core/architecture-of-scala-collections.html"
+ by: Martin Odersky and Lex Spoon
+ description: "These pages describe the architecture of the Scala collections framework in detail. Compared to the Collections API you will find out more about the internal workings of the framework. You will also learn how this architecture helps you define your own collections in a few lines of code, while reusing the overwhelming part of collection functionality from the framework."
diff --git a/_data/setup-scala.yml b/_data/setup-scala.yml
new file mode 100644
index 0000000000..cda4c2361b
--- /dev/null
+++ b/_data/setup-scala.yml
@@ -0,0 +1,6 @@
+linux-x86-64: curl -fL https://github.com/coursier/coursier/releases/latest/download/cs-x86_64-pc-linux.gz | gzip -d > cs && chmod +x cs && ./cs setup
+linux-arm64: curl -fL https://github.com/VirtusLab/coursier-m1/releases/latest/download/cs-aarch64-pc-linux.gz | gzip -d > cs && chmod +x cs && ./cs setup
+macOS-x86-64: curl -fL https://github.com/coursier/coursier/releases/latest/download/cs-x86_64-apple-darwin.gz | gzip -d > cs && chmod +x cs && (xattr -d com.apple.quarantine cs || true) && ./cs setup
+macOS-arm64: curl -fL https://github.com/VirtusLab/coursier-m1/releases/latest/download/cs-aarch64-apple-darwin.gz | gzip -d > cs && chmod +x cs && (xattr -d com.apple.quarantine cs || true) && ./cs setup
+macOS-brew: brew install coursier && coursier setup
+windows-link: https://github.com/coursier/coursier/releases/latest/download/cs-x86_64-pc-win32.zip
diff --git a/_data/sip-data.yml b/_data/sip-data.yml
index 6a6b19fe68..0a351b24da 100644
--- a/_data/sip-data.yml
+++ b/_data/sip-data.yml
@@ -1,27 +1,47 @@
+design:
+ color: "#839496"
+ text: "Design"
+
+implementation:
+ color: "#839496"
+ text: "Implementation"
+
+submitted:
+ color: "#2aa198"
+ text: "Submitted"
+
under-review:
color: "#b58900"
text: "Under Review"
-pending:
+vote-requested:
color: "#b58900"
- text: "Pending"
-
-dormant:
- color: "#839496"
- text: "Dormant"
+ text: "Vote Requested"
-under-revision:
- color: "#2aa198"
- text: "Under Revision"
+waiting-for-implementation:
+ color: "#b58900"
+ text: "Waiting for Implementation"
accepted:
color: "#859900"
text: "Accepted"
-complete:
+shipped:
color: "#859900"
- text: "Complete"
+ text: "Shipped"
rejected:
color: "#dc322f"
text: "Rejected"
+
+withdrawn:
+ color: "#839496"
+ text: "Withdrawn"
+
+accept:
+ color: "#859900"
+ text: "Accept"
+
+reject:
+ color: "#dc322f"
+ text: "Reject"
diff --git a/_data/translations.yml b/_data/translations.yml
index 3641a04203..80ab5afc1c 100644
--- a/_data/translations.yml
+++ b/_data/translations.yml
@@ -1,2 +1,2 @@
tour:
- languages: [ba, es, ko, pt-br, pl, zh-cn, th]
+ languages: [ba, es, fr, ko, pt-br, pl, zh-cn, th, ru, ja]
diff --git a/_de/tutorials/scala-for-java-programmers.md b/_de/tutorials/scala-for-java-programmers.md
index 451cc0a940..9055d7caea 100644
--- a/_de/tutorials/scala-for-java-programmers.md
+++ b/_de/tutorials/scala-for-java-programmers.md
@@ -3,8 +3,6 @@ layout: singlepage-overview
title: Ein Scala Tutorial für Java Programmierer
partof: scala-for-java-programmers
-
-discourse: false
language: de
---
@@ -25,7 +23,7 @@ einfach ist, eignet es sich sehr gut, Scalas Funktionsweise zu demonstrieren, oh
über die Sprache wissen muss.
object HalloWelt {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
println("Hallo, Welt!")
}
}
@@ -95,7 +93,7 @@ Klassen der Java-Pakete importieren:
import java.text.DateFormat._
object FrenchDate {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format now)
@@ -147,24 +145,10 @@ der folgende
exklusiv aus Methoden-Aufrufen, da es äquivalent zu folgendem Ausdruck ist, wie in vorhergehenden
Abschnitt gezeigt wurde:
- (1).+(((2).*(3))./(x))
+ 1.+(2.*(3)./(x))
Dies bedeutet außerdem, dass `+`, `*`, etc. in Scala gültige Bezeichner sind.
-Die Zahlen umschließenden Klammern der zweiten Variante sind notwendig, weil Scalas lexikalischer
-Scanner eine Regel zur längsten Übereinstimmung der Token verwendet. Daher würde der folgende
-Ausdruck:
-
- 1.+(2)
-
-in die Token `1.`, `+`, und `2` zerlegt werden. Der Grund für diese Zerlegung ist, dass `1.` eine
-längere, gültige Übereinstimmung ist, als `1`. Daher würde das Token `1.` als das Literal `1.0`
-interpretiert, also als Gleitkommazahl anstatt als Ganzzahl. Den Ausdruck als
-
- (1).+(2)
-
-zu schreiben, verhindert also, dass `1.` als Gleitkommazahl interpretiert wird.
-
### Funktionen sind Objekte
Vermutlich überraschender für Java-Programmierer ist, dass auch Funktionen in Scala Objekte sind.
@@ -199,7 +183,7 @@ einmal pro Sekunde aus.
println("Die Zeit vergeht wie im Flug.")
}
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
oncePerSecond(timeFlies)
}
}
@@ -225,7 +209,7 @@ Variante des obigen Timer-Programmes verwendet eine anonyme Funktion anstatt der
}
}
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
oncePerSecond(() => println("Die Zeit vergeht wie im Flug."))
}
}
@@ -272,7 +256,7 @@ Ein Problem der obigen Methoden `re` und `im` ist, dass man, um sie zu verwenden
Klammerpaar hinter ihren Namen anhängen muss:
object ComplexNumbers {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val c = new Complex(1.2, 3.4)
println("imaginary part: " + c.im())
}
@@ -449,7 +433,7 @@ noch aus. Zu diesem Zweck soll eine `main`-Methode dienen, die den Ausdruck `(x+
Beispiel verwendet: zuerst wird der Wert in der Umgebung `{ x -> 5, y -> 7 }` berechnet und darauf
die beiden partiellen Ableitungen gebildet:
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val exp: Tree = Sum(Sum(Var("x"),Var("x")),Sum(Const(7),Var("y")))
val env: Environment = {
case "x" => 5
@@ -613,7 +597,7 @@ Um diese Referenz-Klasse zu verwenden, muss der generische Typ bei der Erzeugung
angegeben werden. Für einen Ganzzahl-Container soll folgendes Beispiel dienen:
object IntegerReference {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val cell = new Reference[Int]
cell.set(13)
println("Reference contains the half of " + (cell.get * 2))
diff --git a/_es/overviews/core/actors.md b/_es/overviews/core/actors.md
deleted file mode 100644
index 8c74bcf92e..0000000000
--- a/_es/overviews/core/actors.md
+++ /dev/null
@@ -1,497 +0,0 @@
----
-layout: singlepage-overview
-title: API de actores en Scala
-
-partof: actors
-
-language: es
-
-discourse: false
----
-
-**Philipp Haller and Stephen Tu**
-
-**Traducción e interpretación: Miguel Ángel Pastor Olivar**
-
-## Introducción
-
-La presente guía describe el API del paquete `scala.actors` de Scala 2.8/2.9. El documento se estructura en diferentes grupos lógicos. La jerarquía de "traits" es tenida en cuenta para llevar a cabo la estructuración de las secciones individuales. La atención se centra en el comportamiento exhibido en tiempo de ejecución por varios de los métodos presentes en los traits anteriores, complementando la documentación existente en el Scaladoc API.
-
-## Traits de actores: Reactor, ReplyReactor, y Actor
-
-### The Reactor trait
-
-`Reactor` es el padre de todos los traits relacionados con los actores. Heredando de este trait podremos definir actores con una funcionalidad básica de envío y recepción de mensajes.
-
-El comportamiento de un `Reactor` se define mediante la implementación de su método `act`. Este método es ejecutado una vez el `Reactor` haya sido iniciado mediante la invocación del método `start`, retornando el `Reactor`. El método `start`es *idempotente*, lo cual significa que la invocación del mismo sobre un actor que ya ha sido iniciado no surte ningún efecto.
-
-El trait `Reactor` tiene un parámetro de tipo `Msg` el cual determina el tipo de mensajes que un actor es capaz de recibir.
-
-La invocación del método `!` de un `Reactor` envía un mensaje al receptor. La operación de envío de un mensaje mediante el operador `!` es asíncrona por lo que el actor que envía el mensaje no se bloquea esperando a que el mensaje sea recibido sino que su ejecución continua de manera inmediata. Por ejemplo, `a ! msg` envia `msg` a `a`. Todos los actores disponen de un *buzón* encargado de regular los mensajes entrantes hasta que son procesados.
-
-El trait `Reactor` trait también define el método `forward`. Este método es heredado de `OutputChannel` y tiene el mismo efecto que el método `!`. Aquellos traits que hereden de `Reactor`, en particular el trait `ReplyActor`, sobreescriben este método para habilitar lo que comunmente se conocen como *"implicit reply destinations"* (ver a continuación)
-
-Un `Reactor` recibe mensajes utilizando el método `react`. Este método espera un argumento de tipo `PartialFunction[Msg, Unit]` el cual define cómo los mensajes de tipo `Msg` son tratados una vez llegan al buzón de un actor. En el siguiente ejemplo, el actor espera recibir la cadena "Hello", para posteriomente imprimir un saludo:
-
- react {
- case "Hello" => println("Hi there")
- }
-
-La invocación del método `react` nunca retorna. Por tanto, cualquier código que deba ejecutarse tras la recepción de un mensaje deberá ser incluido dentro de la función parcial pasada al método `react`. Por ejemplo, dos mensajes pueden ser recibidos secuencialmente mediante la anidación de dos llamadas a `react`:
-
- react {
- case Get(from) =>
- react {
- case Put(x) => from ! x
- }
- }
-
-El trait `Reactor` también ofrece una serie de estructuras de control que facilitan la programación utilizando el mecanismo de `react`.
-
-#### Terminación y estados de ejecución
-
-La ejecución de un `Reactor` finaliza cuando el cuerpo del método `act` ha sido completado. Un `Reactor` también pueden terminarse a si mismo de manera explícita mediante el uso del método `exit`. El tipo de retorno de `exit` es `Nothing`, dado que `exit` siempre dispara una excepción. Esta excepción únicamente se utiliza de manera interna y nunca debería ser capturada.
-
-Un `Reactor` finalizado pueden ser reiniciado mediante la invocación de su método `restart`. La invocación del método anterior sobre un `Reactor` que no ha terminado su ejecución lanza una excepción de tipo `IllegalStateException`. El reinicio de un actor que ya ha terminado provoca que el método `act` se ejecute nuevamente.
-
-El tipo `Reactor` define el método `getState`, el cual retorna, como un miembro de la enumeración `Actor.State`, el estado actual de la ejecución del actor. Un actor que todavía no ha sido iniciado se encuentra en el estado `Actor.State.New`. Si el actor se está ejecutando pero no está esperando por ningún mensaje su estado será `Actor.State.Runnable`. En caso de que el actor haya sido suspendido mientras espera por un mensaje estará en el estado `Actor.State.Suspended`. Por último, un actor ya terminado se encontrará en el estado `Actor.State.Terminated`.
-
-#### Manejo de excepciones
-
-El miembro `exceptionHandler` permite llevar a cabo la definición de un manejador de excepciones que estará habilitado durante toda la vida del `Reactor`:
-
- def exceptionHandler: PartialFunction[Exception, Unit]
-
-Este manejador de excepciones (`exceptionHandler`) retorna una función parcial que se utiliza para gestionar excepciones que no hayan sido tratadas de ninguna otra manera. Siempre que una excepción se propague fuera del método `act` de un `Reactor` el manejador anterior será aplicado a dicha excepción, permitiendo al actor ejecutar código de limpieza antes de que se termine. Nótese que la visibilidad de `exceptionHandler` es `protected`.
-
-El manejo de excepciones mediante el uso de `exceptionHandler` encaja a la perfección con las estructuras de control utilizadas para programas con el método `react`. Siempre que una excepción es manejada por la función parcial retornada por `excepctionHandler`, la ejecución continua con la "closure" actual:
-
- loop {
- react {
- case Msg(data) =>
- if (cond) // process data
- else throw new Exception("cannot process data")
- }
- }
-
-Assumiendo que `Reactor` sobreescribe el atributo `exceptionHandler`, tras el lanzamiento de una excepción en el cuerpo del método `react`, y una vez ésta ha sido gestionada, la ejecución continua con la siguiente iteración del bucle.
-
-### The ReplyReactor trait
-
-El trait `ReplyReactor` extiende `Reactor[Any]` y sobrescribe y/o añade los siguientes métodos:
-
-- El método `!` es sobrescrito para obtener una referencia al actor
- actual (el emisor). Junto al mensaje actual, la referencia a dicho
- emisor es enviada al buzón del actor receptor. Este último dispone de
- acceso al emisor del mensaje mediante el uso del método `sender` (véase más abajo).
-
-- El método `forward` es sobrescrito para obtener una referencia al emisor
- del mensaje que actualmente está siendo procesado. Junto con el mensaje
- actual, esta referencia es enviada como el emisor del mensaje actual.
- Como consuencia de este hecho, `forward` nos permite reenviar mensajes
- en nombre de actores diferentes al actual.
-
-- El método (añadido) `sender` retorna el emisor del mensaje que está siendo
- actualmente procesado. Puesto que un mensaje puede haber sido reenviado,
- `sender` podría retornar un actor diferente al que realmente envió el mensaje.
-
-- El método (añadido) `reply` envía una respuesta al emisor del último mensaje.
- `reply` también es utilizado para responder a mensajes síncronos o a mensajes
- que han sido enviados mediante un "future" (ver más adelante).
-
-- El método (añadido) `!?` ofrece un *mecanismo síncrono de envío de mensajes*.
- La invocación de `!?` provoca que el actor emisor del mensaje se bloquee hasta
- que se recibe una respuesta, momento en el cual retorna dicha respuesta. Existen
- dos variantes sobrecargadas. La versión con dos parámetros recibe un argumento
- adicional que representa el tiempo de espera (medido en milisegundos) y su tipo
- de retorno es `Option[Any]` en lugar de `Any`. En caso de que el emisor no
- reciba una respuesta en el periodo de espera establecido, el método `!?` retornará
- `None`; en otro caso retornará la respuesta recibida recubierta con `Some`.
-
-- Los métodos (añadidos) `!!` son similares al envío síncrono de mensajes en el sentido de
- que el receptor puede enviar una respuesta al emisor del mensaje. Sin embargo, en lugar
- de bloquear el actor emisor hasta que una respuesta es recibida, retornan una instancia de
- `Future`. Esta última puede ser utilizada para recuperar la respuesta del receptor una
- vez se encuentre disponible; asimismo puede ser utilizada para comprobar si la respuesta
- está disponible sin la necesidad de bloquear el emisor. Existen dos versiones sobrecargadas.
- La versión que acepta dos parámetros recibe un argumento adicional de tipo
- `PartialFunction[Any, A]`. Esta función parcial es utilizada para realizar el post-procesado de
- la respuesta del receptor. Básicamente, `!!` retorna un "future" que aplicará la anterior
- función parcial a la repuesta (una vez recibida). El resultado del "future" es el resultado
- de este post-procesado.
-
-- El método (añadido) `reactWithin` permite llevar a cabo la recepción de mensajes en un periodo
- determinado de tiempo. En comparación con el método `react`, recibe un parámetro adicional,
- `msec`, el cual representa el periodo de tiempo, expresado en milisegundos, hasta que el patrón `TIMEOUT`
- es satisfecho (`TIMEOUT` es un "case object" presente en el paquete `scala.actors`). Ejemplo:
-
- reactWithin(2000) {
- case Answer(text) => // process text
- case TIMEOUT => println("no answer within 2 seconds")
- }
-
-- El método `reactWithin` también permite realizar accesos no bloqueantes al buzón. Si
- especificamos un tiempo de espera de 0 milisegundos, primeramente el buzón será escaneado
- en busca de un mensaje que concuerde. En caso de que no exista ningún mensaje concordante
- tras el primer escaneo, el patrón `TIMEOUT` será satisfecho. Por ejemplo, esto nos permite
- recibir determinado tipo de mensajes donde unos tienen una prioridad mayor que otros:
-
- reactWithin(0) {
- case HighPriorityMsg => // ...
- case TIMEOUT =>
- react {
- case LowPriorityMsg => // ...
- }
- }
-
- En el ejemplo anterior, el actor procesa en primer lugar los mensajes `HighPriorityMsg` aunque
- exista un mensaje `LowPriorityMsg` más antiguo en el buzón. El actor sólo procesará mensajes
- `LowPriorityMsg` en primer lugar en aquella situación donde no exista ningún `HighProrityMsg`
- en el buzón.
-
-Adicionalmente, el tipo `ReplyActor` añade el estado de ejecución `Actor.State.TimedSuspended`. Un actor suspendido, esperando la recepción de un mensaje mediante el uso de `reactWithin` se encuentra en dicho estado.
-
-### El trait Actor
-
-El trait `Actor` extiende de `ReplyReactor` añadiendo y/o sobrescribiendo los siguientes miembros:
-
-- El método (añadido) `receive` se comporta del mismo modo que `react`, con la excepción
- de que puede retornar un resultado. Este hecho se ve reflejado en la definición del tipo,
- que es polimórfico en el tipo del resultado: `def receive[R](f: PartialFunction[Any, R]): R`.
- Sin embargo, la utilización de `receive` hace que el uso del actor
- sea más pesado, puesto que el hilo subyacente es bloqueado mientras
- el actor está esperando por la respuesta. El hilo bloqueado no está
- disponible para ejecutar otros actores hasta que la invocación del
- método `receive` haya retornado.
-
-- El método (añadido) `link` permite a un actor enlazarse y desenlazarse de otro
- actor respectivamente. El proceso de enlazado puede utilizarse para monitorizar
- y responder a la terminación de un actor. En particular, el proceso de enlazado
- afecta al comportamiento mostrado en la ejecución del método `exit` tal y como
- se escribe en el la documentación del API del trait `Actor`.
-
-- El atributo `trapExit` permite responder a la terminación de un actor enlazado,
- independientemente de los motivos de su terminación (es decir, carece de importancia
- si la terminación del actor es normal o no). Si `trapExit` toma el valor cierto en
- un actor, este nunca terminará por culpa de los actores enlazados. En cambio, siempre
- y cuando uno de sus actores enlazados finalice, recibirá un mensaje de tipo `Exit`.
- `Exit` es una "case class" que presenta dos atributos: `from` referenciando al actor
- que termina y `reason` conteniendo los motivos de la terminación.
-
-#### Terminación y estados de ejecución
-
-Cuando la ejecución de un actor finaliza, el motivo de dicha terminación puede ser
-establecida de manera explícita mediante la invocación de la siguiente variante
-del método `exit`:
-
- def exit(reason: AnyRef): Nothing
-
-Un actor cuyo estado de terminación es diferente del símbolo `'normal` propaga
-los motivos de su terminación a todos aquellos actores que se encuentren enlazados
-a él. Si el motivo de la terminación es una excepción no controlada, el motivo de
-finalización será una instancia de la "case class" `UncaughtException`.
-
-El trait `Actor` incluye dos nuevos estados de ejecución. Un actor que se encuentra
-esperando la recepción de un mensaje mediante la utilización del método `receive` se
-encuentra en el método `Actor.State.Blocked`. Un actor esperado la recepción de un
-mensaje mediante la utilización del método `receiveWithin` se encuentra en el estado
-`Actor.State.TimeBlocked`.
-
-## Estructuras de control
-
-El trait `Reactor` define una serie de estructuras de control que simplifican el mecanismo
-de programación con la función sin retorno `react`. Normalmente, una invocación al método
-`react` no retorna nunca. Si el actor necesita ejecutar código a continuación de la invocación
-anterior, tendrá que pasar, de manera explícita, dicho código al método `react` o utilizar
-algunas de las estructuras que encapsulan este comportamiento.
-
-La estructura de control más basica es `andThen`. Permite registrar una `closure` que será
-ejecutada una vez el actor haya terminado la ejecución de todo lo demas.
-
- actor {
- {
- react {
- case "hello" => // processing "hello"
- }: Unit
- } andThen {
- println("hi there")
- }
- }
-
-Por ejemplo, el actor anterior imprime un saludo tras realizar el procesado
-del mensaje `hello`. Aunque la invocación del método `react` no retorna,
-podemos utilizar `andThen` para registrar el código encargado de imprimir
-el saludo a continuación de la ejecución del actor.
-
-Nótese que existe una *atribución de tipo* a continuación de la invocación
-de `react` (`:Unit`). Básicamente, nos permite tratar el resultado de
-`react` como si fuese de tipo `Unit`, lo cual es legal, puesto que el resultado
-de una expresión siempre se puede eliminar. Es necesario llevar a cabo esta operación
-dado que `andThen` no puede ser un miembro del tipo `Unit`, que es el tipo del resultado
-retornado por `react`. Tratando el tipo de resultado retornado por `react` como
-`Unit` permite llevar a cabo la aplicación de una conversión implícita la cual
-hace que el miembro `andThen` esté disponible.
-
-El API ofrece unas cuantas estructuras de control adicionales:
-
-- `loop { ... }`. Itera de manera indefinidia, ejecutando el código entre
-las llaves en cada una de las iteraciones. La invocación de `react` en el
-cuerpo del bucle provoca que el actor se comporte de manera habitual ante
-la llegada de un nuevo mensaje. Posteriormente a la recepción del mensaje,
-la ejecución continua con la siguiente iteración del bucle actual.
-
-- `loopWhile (c) { ... }`. Ejecuta el código entre las llaves mientras la
-condición `c` tome el valor `true`. La invocación de `react` en el cuerpo
-del bucle ocasiona el mismo efecto que en el caso de `loop`.
-
-- `continue`. Continua con la ejecución de la closure actual. La invocación
-de `continue` en el cuerpo de un `loop`o `loopWhile` ocasionará que el actor
-termine la iteración en curso y continue con la siguiente. Si la iteración en
-curso ha sido registrada utilizando `andThen`, la ejecución continua con la
-segunda "closure" pasada como segundo argumento a `andThen`.
-
-Las estructuras de control pueden ser utilizadas en cualquier parte del cuerpo
-del método `act` y en los cuerpos de los métodos que, transitivamente, son
-llamados por `act`. Aquellos actores creados utilizando la sintáxis `actor { ... }`
-pueden importar las estructuras de control desde el objeto `Actor`.
-
-#### Futures
-
-Los traits `RepyActor` y `Actor` soportan operaciones de envío de mensajes
-(métodos `!!`) que, de manera inmediata, retornan un *future*. Un *future*,
-es una instancia del trait `Future` y actúa como un manejador que puede
-ser utilizado para recuperar la respuesta a un mensaje "send-with-future".
-
-El emisor de un mensaje "send-with-future" puede esperar por la respuesta del
-future *aplicando* dicha future. Por ejemplo, el envío de un mensaje mediante
-`val fut = a !! msg` permite al emisor esperar por el resultado del future
-del siguiente modo: `val res = fut()`.
-
-Adicionalmente, utilizando el método `isSet`, un `Future` puede ser consultado
-de manera no bloqueante para comprobar si el resultado está disponible.
-
-Un mensaje "send-with-future" no es el único modo de obtener una referencia a
-un future. Estos pueden ser creados utilizando el método `future`. En el siguiente
-ejemplo, `body` se ejecuta de manera concurrente, retornando un future como
-resultado.
-
- val fut = Future { body }
- // ...
- fut() // wait for future
-
-Lo que hace especial a los futures en el contexto de los actores es la posibilidad
-de recuperar su resultado utilizando las operaciones estándar de actores de
-recepción de mensajes como `receive`, etc. Además, es posible utilizar las operaciones
-basadas en eventos `react`y `reactWithin`. Esto permite a un actor esperar por el
-resultado de un future sin la necesidad de bloquear el hilo subyacente.
-
-Las operaciones de recepción basadas en actores están disponibles a través del
-atributo `inputChannel` del future. Dado un future de tipo `Future[T]`, el tipo
-de `inputChannel` es `InputChannel[T]`. Por ejemplo:
-
- val fut = a !! msg
- // ...
- fut.inputChannel.react {
- case Response => // ...
- }
-
-## Canales
-
-Los canales pueden ser utilizados para simplificar el manejo de mensajes
-que presentan tipos diferentes pero que son enviados al mismo actor. La
-jerarquía de canales se divide en `OutputChannel` e `InputChannel`.
-
-Los `OutputChannel` pueden ser utilizados para enviar mensajes. Un
-`OutputChannel` `out` soporta las siguientes operaciones:
-
-- `out ! msg`. Envía el mensaje `msg` a `out` de manera asíncrona. Cuando `msg`
- es enviado directamente a un actor se incluye un referencia al actor emisor
- del mensaje.
-
-- `out forward msg`. Reenvía el mensaje `msg` a `out` de manera asíncrona.
- El actor emisor se determina en el caso en el que `msg` es reenviado a
- un actor.
-
-- `out.receiver`. Retorna el único actor que está recibiendo mensajes que están
- siendo enviados al canal `out`.
-
-- `out.send(msg, from)`. Envía el mensaje `msg` a `out` de manera asíncrona,
- proporcionando a `from` como el emisor del mensaje.
-
-Nótese que el trait `OutputChannel` tiene un parámetro de tipo que especifica el
-tipo de los mensajes que pueden ser enviados al canal (utilizando `!`, `forward`,
-y `send`). Este parámetro de tipo es contra-variante:
-
- trait OutputChannel[-Msg]
-
-Los actores pueden recibir mensajes de un `InputChannel`. Del mismo modo que
-`OutputChannel`, el trait `InputChannel` presenta un parámetro de tipo que
-especifica el tipo de mensajes que pueden ser recibidos por el canal. En este caso,
-el parámetro de tipo es covariante:
-
- trait InputChannel[+Msg]
-
-Un `InputChannel[Msg]` `in` soportal las siguientes operaciones.
-
-- `in.receive { case Pat1 => ... ; case Patn => ... }` (y de manera similar,
- `in.receiveWithin`) recibe un mensaje proveniente de `in`. La invocación
- del método `receive` en un canal de entrada presenta la misma semántica
- que la operación estándar de actores `receive`. La única diferencia es que
- la función parcial pasada como argumento tiene tipo `PartialFunction[Msg, R]`
- donde `R` es el tipo de retorno de `receive`.
-
-- `in.react { case Pat1 => ... ; case Patn => ... }` (y de manera similar,
- `in.reactWithin`). Recibe un mensaje de `in` utilizando la operación basada en
- eventos `react`. Del mismo modo que la operación `react` en actores, el tipo
- de retorno es `Nothing`, indicando que las invocaciones de este método nunca
- retornan. Al igual que la operación `receive` anterior, la función parcial
- que se pasa como argumento presenta un tipo más específico:
-
- PartialFunction[Msg, Unit]
-
-### Creando y compartiendo canales
-
-Los canales son creados utilizando la clase concreta `Channel`. Esta clase extiende
-de `InputChannel` y `OutputChannel`. Un canal pueden ser compartido haciendo dicho
-canal visible en el ámbito de múltiples actores o enviándolo como mensaje.
-
-El siguiente ejemplo muestra la compartición mediante publicación en ámbitos:
-
- actor {
- var out: OutputChannel[String] = null
- val child = actor {
- react {
- case "go" => out ! "hello"
- }
- }
- val channel = new Channel[String]
- out = channel
- child ! "go"
- channel.receive {
- case msg => println(msg.length)
- }
- }
-
-La ejecución de este ejemplo imprime la cadena "5" en la consola. Nótese que el
-actor `child` únicamente tiene acceso a `out`, que es un `OutputChannel[String]`.
-La referencia al canal, la cual puede ser utilizada para llevar a cabo la recepción
-de mensajes, se encuentra oculta. Sin embargo, se deben tomar precauciones y
-asegurarse que el canal de salida es inicializado con un canal concreto antes de que
-`child` le envíe ningún mensaje. En el ejemplo que nos ocupa, esto es llevado a cabo
-mediante el mensaje "go". Cuando se está recibiendo de `channel` utilizando el método
-`channel.receive` podemos hacer uso del hecho que `msg` es de tipo `String`, y por
-lo tanto tiene un miembro `length`.
-
-Una alternativa a la compartición de canales es enviarlos a través de mensajes.
-El siguiente fragmento de código muestra un sencillo ejemplo de aplicación:
-
- case class ReplyTo(out: OutputChannel[String])
-
- val child = actor {
- react {
- case ReplyTo(out) => out ! "hello"
- }
- }
-
- actor {
- val channel = new Channel[String]
- child ! ReplyTo(channel)
- channel.receive {
- case msg => println(msg.length)
- }
- }
-
-La "case class" `ReplyTo` es un tipo de mensajes que utilizamos para distribuir
-una referencia a un `OutputChannel[String]`. Cuando el actor `child` recibe un
-mensaje de tipo `ReplyTo` éste envía una cadena a su canal de salida. El segundo
-actor recibe en el canal del mismo modo que anteriormente.
-
-## Planificadores
-
-Un `Reactor`(o una instancia de uno de sus subtipos) es ejecutado utilizando un
-*planificador*. El trait `Reactor` incluye el miembro `scheduler` el cual retorna el
-planificador utilizado para ejecutar sus instancias:
-
- def scheduler: IScheduler
-
-La plataforma de ejecución ejecuta los actores enviando tareas al planificador mediante
-el uso de los métodos `execute` definidos en el trait `IScheduler`. La mayor parte
-del resto de métodos definidos en este trait únicamente adquieren cierto protagonismo
-cuando se necesita implementar un nuevo planificador desde cero; algo que no es necesario
-en muchas ocasiones.
-
-Los planificadores por defecto utilizados para ejecutar instancias de `Reactor` y
-`Actor` detectan cuando los actores han finalizado su ejecución. En el momento que esto
-ocurre, el planificador se termina a si mismo (terminando con cualquier hilo que estuviera
-en uso por parte del planificador). Sin embargo, algunos planificadores como el
-`SingleThreadedScheduler` (definido en el paquete `scheduler`) necesita ser terminado de
-manera explícita mediante la invocación de su método `shutdown`).
-
-La manera más sencilla de crear un planificador personalizado consisten en extender la clase
-`SchedulerAdapter`, implementando el siguiente método abstracto:
-
- def execute(fun: => Unit): Unit
-
-Por norma general, una implementación concreata utilizaría un pool de hilos para llevar a cabo
-la ejecución del argumento por nombre `fun`.
-
-## Actores remotos
-
-Esta sección describe el API de los actores remotos. Su principal interfaz es el objecto
-[`RemoteActor`](http://www.scala-lang.org/api/2.9.1/scala/actors/remote/RemoteActor$.html) definido
-en el paquete `scala.actors.remote`. Este objeto facilita el conjunto de métodos necesarios para crear
-y establecer conexiones a instancias de actores remotos. En los fragmentos de código que se muestran a
-continuación se asume que todos los miembros de `RemoteActor` han sido importados; la lista completa
-de importaciones utilizadas es la siguiente:
-
- import scala.actors._
- import scala.actors.Actor._
- import scala.actors.remote._
- import scala.actors.remote.RemoteActor._
-
-### Iniciando actores remotos
-
-Un actore remot es identificado de manera unívoca por un
-[`Symbol`](http://www.scala-lang.org/api/2.9.1/scala/Symbol.html). Este símbolo es único para la instancia
-de la máquina virual en la que se está ejecutando un actor. Un actor remoto identificado con el nombre
-`myActor` puede ser creado del siguiente modo.
-
- class MyActor extends Actor {
- def act() {
- alive(9000)
- register('myActor, self)
- // ...
- }
- }
-
-Nótese que el nombre únicamente puede ser registrado con un único actor al mismo tiempo.
-Por ejemplo, para registrar el actor *A* como `'myActor` y posteriormente registrar otro
-actor *B* como `'myActor`, debería esperar hasta que *A* haya finalizado. Este requisito
-aplica a lo largo de todos los puertos, por lo que registrando a *B* en un puerto diferente
-no sería suficiente.
-
-### Connecting to remote actors
-
-Establecer la conexión con un actor remoto es un proceso simple. Para obtener una referencia remota
-a un actor remoto que está ejecutándose en la máquina `myMachine` en el puerto 8000 con el nombre
-`'anActor`, tendremos que utilizar `select`del siguiente modo:
-
- val myRemoteActor = select(Node("myMachine", 8000), 'anActor)
-
-El actor retornado por `select` es de tipo `AbstractActor`, que proporciona esencialmente el mismo
-interfaz que un actor normal, y por lo tanto es compatible con las habituales operaciones de envío
-de mensajes:
-
- myRemoteActor ! "Hello!"
- receive {
- case response => println("Response: " + response)
- }
- myRemoteActor !? "What is the meaning of life?" match {
- case 42 => println("Success")
- case oops => println("Failed: " + oops)
- }
- val future = myRemoteActor !! "What is the last digit of PI?"
-
-Nótese que la operación `select` es perezosa; no inicializa ninguna conexión de red. Simplemente crea
-una nueva instancia de `AbstractActor` que está preparada para iniciar una nueva conexión de red en el
-momento en que sea necesario (por ejemplo cuando el método '!' es invocado).
diff --git a/_es/overviews/core/string-interpolation.md b/_es/overviews/core/string-interpolation.md
index 392a0b68ac..a85787d382 100644
--- a/_es/overviews/core/string-interpolation.md
+++ b/_es/overviews/core/string-interpolation.md
@@ -5,8 +5,6 @@ title: Interpolación de cadenas
partof: string-interpolation
language: es
-
-discourse: false
---
**Josh Suereth**
@@ -21,7 +19,7 @@ Este nuevo mecanismo permite a los usuarios incluir referencias a variables de m
val name = "James"
println(s"Hello, $name") // Hello, James
-En el ejemplo anterior, el literal `s"Hello, $name"` es una cadena "procesada". Esto significa que el compilador debe realizar un trabajo adicional durante el tratamiento de dicha cadena. Una cadena "procesada" se denota mediante un conjunto de caracteres que preceden al símbolo `"`. La interpolación de cadenas ha sido introducida por [SIP-11](http://docs.scala-lang.org/sips/pending/string-interpolation.html), el cual contiene todos los detalles de implementación.
+En el ejemplo anterior, el literal `s"Hello, $name"` es una cadena "procesada". Esto significa que el compilador debe realizar un trabajo adicional durante el tratamiento de dicha cadena. Una cadena "procesada" se denota mediante un conjunto de caracteres que preceden al símbolo `"`. La interpolación de cadenas ha sido introducida por [SIP-11](https://docs.scala-lang.org/sips/pending/string-interpolation.html), el cual contiene todos los detalles de implementación.
## Uso
@@ -61,7 +59,7 @@ El interpolador `f` es seguro respecto a tipos. Si pasamos un número real a una
f"$height%4d"
^
-El interpolador `f` hace uso de las utilidades de formateo de cadenas disponibles en java. Los formatos permitidos tras el carácter `%` son descritos en [Formatter javadoc](http://docs.oracle.com/javase/1.6.0/docs/api/java/util/Formatter.html#detail). Si el carácter `%` no aparece tras la definición de una variable, `%s` es utilizado por defecto.
+El interpolador `f` hace uso de las utilidades de formateo de cadenas disponibles en java. Los formatos permitidos tras el carácter `%` son descritos en [Formatter javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#detail). Si el carácter `%` no aparece tras la definición de una variable, `%s` es utilizado por defecto.
### Interpolador `raw`
@@ -87,7 +85,7 @@ En Scala, todas las cadenas "procesadas" son simples transformaciones de código
id"string content"
-la transforma en la llamada a un método (`id`) sobre una instancia de [StringContext](http://www.scala-lang.org/api/current/index.html#scala.StringContext). Este método también puede estar disponible en un ámbito implícito. Para definiir nuestra propia cadena de interpolación simplemente necesitamos crear una clase implícita que añada un nuevo método a la clase `StringContext`. A continuación se muestra un ejemplo:
+la transforma en la llamada a un método (`id`) sobre una instancia de [StringContext](https://www.scala-lang.org/api/current/index.html#scala.StringContext). Este método también puede estar disponible en un ámbito implícito. Para definiir nuestra propia cadena de interpolación simplemente necesitamos crear una clase implícita que añada un nuevo método a la clase `StringContext`. A continuación se muestra un ejemplo:
// Note: We extends AnyVal to prevent runtime instantiation. See
// value class guide for more info.
@@ -115,10 +113,10 @@ De este modo, el método `json` tiene acceso a las diferentes partes de las cade
def json(args: Any*): JSONObject = {
val strings = sc.parts.iterator
val expressions = args.iterator
- var buf = new StringBuffer(strings.next)
+ var buf = new StringBuilder(strings.next)
while(strings.hasNext) {
- buf append expressions.next
- buf append strings.next
+ buf.append(expressions.next())
+ buf.append(strings.next())
}
parseJson(buf)
}
diff --git a/_es/overviews/parallel-collections/architecture.md b/_es/overviews/parallel-collections/architecture.md
index fa8d146b00..138a5dee08 100644
--- a/_es/overviews/parallel-collections/architecture.md
+++ b/_es/overviews/parallel-collections/architecture.md
@@ -1,9 +1,6 @@
---
layout: multipage-overview
title: Arquitectura de la librería de colecciones paralelas de Scala
-
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
@@ -90,7 +87,7 @@ de la librería de colecciones secuenciales -- de hecho, "replican" los correspo
traits presentes en el framework de colecciones secuenciales, tal y como se muestra
a continuación.
-[]({{ site.baseurl }}/resources/images/parallel-collections-hierarchy.png)
+[]({{ site.baseurl }}/resources/images/parallel-collections-hierarchy.png)
Jerarquía de clases de las librerías de colecciones secuenciales y paralelas de Scala
@@ -115,4 +112,4 @@ paralelas referirse al artículo \[[1][1]\]
1. [On a Generic Parallel Collection Framework, Aleksandar Prokopec, Phil Bawgell, Tiark Rompf, Martin Odersky, June 2011][1]
-[1]: http://infoscience.epfl.ch/record/165523/files/techrep.pdf "flawed-benchmark"
+[1]: https://infoscience.epfl.ch/record/165523/files/techrep.pdf "flawed-benchmark"
diff --git a/_es/overviews/parallel-collections/concrete-parallel-collections.md b/_es/overviews/parallel-collections/concrete-parallel-collections.md
index 158c923f6e..4674d34b16 100644
--- a/_es/overviews/parallel-collections/concrete-parallel-collections.md
+++ b/_es/overviews/parallel-collections/concrete-parallel-collections.md
@@ -1,9 +1,6 @@
---
layout: multipage-overview
title: Clases Concretas de las Colecciones Paralelas
-
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
@@ -13,7 +10,7 @@ language: es
## Array Paralelo
-Una secuencia [ParArray](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/parallel/mutable/ParArray.html) contiene un conjunto de elementos contiguos lineales. Esto significa que los elementos pueden ser accedidos y actualizados (modificados) eficientemente al modificar la estructura subyacente (un array). El iterar sobre sus elementos es también muy eficiente por esta misma razón. Los Arrays Paralelos son como arrays en el sentido de que su tamaño es constante.
+Una secuencia [ParArray](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/parallel/mutable/ParArray.html) contiene un conjunto de elementos contiguos lineales. Esto significa que los elementos pueden ser accedidos y actualizados (modificados) eficientemente al modificar la estructura subyacente (un array). El iterar sobre sus elementos es también muy eficiente por esta misma razón. Los Arrays Paralelos son como arrays en el sentido de que su tamaño es constante.
scala> val pa = scala.collection.parallel.mutable.ParArray.tabulate(1000)(x => 2 * x + 1)
pa: scala.collection.parallel.mutable.ParArray[Int] = ParArray(1, 3, 5, 7, 9, 11, 13,...
@@ -31,7 +28,7 @@ Al invocar el método `seq`, los arrays paralelos son convertidos al tipo de col
## Vector Paralelo
-Un [ParVector](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/parallel/immutable/ParVector.html) es una secuencia inmutable con un tiempo de acceso y modificación logarítimico bajo a constante.
+Un [ParVector](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/parallel/immutable/ParVector.html) es una secuencia inmutable con un tiempo de acceso y modificación logarítimico bajo a constante.
scala> val pv = scala.collection.parallel.immutable.ParVector.tabulate(1000)(x => x)
pv: scala.collection.parallel.immutable.ParVector[Int] = ParVector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,...
@@ -41,11 +38,11 @@ Un [ParVector](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/coll
Los vectores inmutables son representados por árboles, por lo que los splitters dividen pasándose subárboles entre ellos. Los combiners concurrentemente mantienen un vector de elementos y son combinados al copiar dichos elementos de forma "retardada". Es por esta razón que los métodos tranformadores son menos escalables que sus contrapartes en arrays paralelos. Una vez que las operaciones de concatenación de vectores estén disponibles en una versión futura de Scala, los combiners podrán usar dichas características y hacer más eficientes los métodos transformadores.
-Un vector paralelo es la contraparte paralela de un [Vector](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/immutable/Vector.html) secuencial, por lo tanto la conversión entre estas dos estructuras se efectúa en tiempo constante.
+Un vector paralelo es la contraparte paralela de un [Vector](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/immutable/Vector.html) secuencial, por lo tanto la conversión entre estas dos estructuras se efectúa en tiempo constante.
## Rango (Range) Paralelo
-Un [ParRange](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/parallel/immutable/ParRange.html) es una secuencia ordenada separada por intervalos iguales (ej: 1, 2, 3 o 1, 3, 5, 7). Un rango paralelo es creado de forma similar al [Rango](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/immutable/Range.html) secuencial:
+Un [ParRange](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/parallel/immutable/ParRange.html) es una secuencia ordenada separada por intervalos iguales (ej: 1, 2, 3 o 1, 3, 5, 7). Un rango paralelo es creado de forma similar al [Rango](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/immutable/Range.html) secuencial:
scala> 1 to 3 par
res0: scala.collection.parallel.immutable.ParRange = ParRange(1, 2, 3)
@@ -61,7 +58,7 @@ Tal como los rangos secuenciales no tienen constructores, los rangos paralelos n
## Tablas Hash Paralelas
-Las tablas hash paralelas almacenan sus elementos en un array subyacente y los almacenan en una posición determinada por el código hash del elemento respectivo. Las versiones mutables de los hash sets paralelos ([mutable.ParHashSet](http://www.scala-lang.org/api/{{ site.scala-version}}/scala/collection/parallel/mutable/ParHashSet.html)) y los hash maps paraleos ([mutable.ParHashMap](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/parallel/mutable/ParHashMap.html)) están basados en tablas hash.
+Las tablas hash paralelas almacenan sus elementos en un array subyacente y los almacenan en una posición determinada por el código hash del elemento respectivo. Las versiones mutables de los hash sets paralelos ([mutable.ParHashSet](https://www.scala-lang.org/api/{{ site.scala-212-version}}/scala/collection/parallel/mutable/ParHashSet.html)) y los hash maps paraleos ([mutable.ParHashMap](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/parallel/mutable/ParHashMap.html)) están basados en tablas hash.
scala> val phs = scala.collection.parallel.mutable.ParHashSet(1 until 2000: _*)
phs: scala.collection.parallel.mutable.ParHashSet[Int] = ParHashSet(18, 327, 736, 1045, 773, 1082,...
@@ -75,9 +72,9 @@ Los "Mapas Hash" (Hash Maps) y los "Conjuntos Hash" (Hash Sets) secuenciales pue
## Hash Tries Paralelos
-Los Hash Tries paralelos son la contraparte paralela de los hash tries inmutables, que son usados para representar conjuntos y mapas inmutables de forma eficiente. Las clases involucradas son: [immutable.ParHashSet](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/parallel/immutable/ParHashSet.html)
+Los Hash Tries paralelos son la contraparte paralela de los hash tries inmutables, que son usados para representar conjuntos y mapas inmutables de forma eficiente. Las clases involucradas son: [immutable.ParHashSet](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/parallel/immutable/ParHashSet.html)
y
-[immutable.ParHashMap](http://www.scala-lang.org/api/{{ site.scala-version}}/scala/collection/parallel/immutable/ParHashMap.html).
+[immutable.ParHashMap](https://www.scala-lang.org/api/{{ site.scala-212-version}}/scala/collection/parallel/immutable/ParHashMap.html).
scala> val phs = scala.collection.parallel.immutable.ParHashSet(1 until 1000: _*)
phs: scala.collection.parallel.immutable.ParHashSet[Int] = ParSet(645, 892, 69, 809, 629, 365, 138, 760, 101, 479,...
@@ -92,7 +89,7 @@ Los hash tries paralelos pueden ser convertidos hacia y desde hash tries secuenc
## Tries Paralelos Concurrentes
-Un [concurrent.TrieMap](http://www.scala-lang.org/api/{{ site.scala-version }}/scala/collection/concurrent/TrieMap.html) es un mapa thread-safe (seguro ante la utilización de múltiples hilos concurrentes) mientras que [mutable.ParTrieMap](http://www.scala-lang.org/api/{{ site.scala-version}}/scala/collection/parallel/mutable/ParTrieMap.html) es su contraparte paralela. Si bien la mayoría de las estructuras de datos no garantizan una iteración consistente si la estructura es modificada en medio de dicha iteración, los tries concurrentes garantizan que las actualizaciones sean solamente visibles en la próxima iteración. Esto significa que es posible mutar el trie concurrente mientras se está iterando sobre este, como en el siguiente ejemplo, que computa e imprime las raíces cuadradas de los números entre 1 y 99:
+Un [concurrent.TrieMap](https://www.scala-lang.org/api/{{ site.scala-212-version }}/scala/collection/concurrent/TrieMap.html) es un mapa thread-safe (seguro ante la utilización de múltiples hilos concurrentes) mientras que [mutable.ParTrieMap](https://www.scala-lang.org/api/{{ site.scala-212-version}}/scala/collection/parallel/mutable/ParTrieMap.html) es su contraparte paralela. Si bien la mayoría de las estructuras de datos no garantizan una iteración consistente si la estructura es modificada en medio de dicha iteración, los tries concurrentes garantizan que las actualizaciones sean solamente visibles en la próxima iteración. Esto significa que es posible mutar el trie concurrente mientras se está iterando sobre este, como en el siguiente ejemplo, que computa e imprime las raíces cuadradas de los números entre 1 y 99:
scala> val numbers = scala.collection.parallel.mutable.ParTrieMap((1 until 100) zip (1 until 100): _*) map { case (k, v) => (k.toDouble, v.toDouble) }
numbers: scala.collection.parallel.mutable.ParTrieMap[Double,Double] = ParTrieMap(0.0 -> 0.0, 42.0 -> 42.0, 70.0 -> 70.0, 2.0 -> 2.0,...
diff --git a/_es/overviews/parallel-collections/configuration.md b/_es/overviews/parallel-collections/configuration.md
index 6e921bc9a5..c0c9604254 100644
--- a/_es/overviews/parallel-collections/configuration.md
+++ b/_es/overviews/parallel-collections/configuration.md
@@ -1,9 +1,6 @@
---
layout: multipage-overview
title: Configurando las colecciones paralelas
-
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
@@ -80,4 +77,4 @@ las diferentes tareas.
1. [On a Generic Parallel Collection Framework, June 2011][1]
- [1]: http://infoscience.epfl.ch/record/165523/files/techrep.pdf "parallel-collections"
+ [1]: https://infoscience.epfl.ch/record/165523/files/techrep.pdf "parallel-collections"
diff --git a/_es/overviews/parallel-collections/conversions.md b/_es/overviews/parallel-collections/conversions.md
index 8461a2f9aa..dd3caa1543 100644
--- a/_es/overviews/parallel-collections/conversions.md
+++ b/_es/overviews/parallel-collections/conversions.md
@@ -1,8 +1,6 @@
---
layout: multipage-overview
title: Conversiones en colecciones paralelas
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
@@ -61,16 +59,16 @@ en una colección `ParX`
A continuación se muestra un resumen de todos los métodos de conversión:
-| método | Tipo de Retorno|
-| -------------- | -------------- |
-| `toArray` | `Array` |
-| `toList` | `List` |
-| `toIndexedSeq` | `IndexedSeq` |
-| `toStream` | `Stream` |
-| `toIterator` | `Iterator` |
-| `toBuffer` | `Buffer` |
-| `toTraversable`| `GenTraverable`|
-| `toIterable` | `ParIterable` |
-| `toSeq` | `ParSeq` |
-| `toSet` | `ParSet` |
-| `toMap` | `ParMap` |
+| método | Tipo de Retorno |
+| -------------- | --------------- |
+| `toArray` | `Array` |
+| `toList` | `List` |
+| `toIndexedSeq` | `IndexedSeq` |
+| `toStream` | `Stream` |
+| `toIterator` | `Iterator` |
+| `toBuffer` | `Buffer` |
+| `toTraversable`| `GenTraversable`|
+| `toIterable` | `ParIterable` |
+| `toSeq` | `ParSeq` |
+| `toSet` | `ParSet` |
+| `toMap` | `ParMap` |
diff --git a/_es/overviews/parallel-collections/ctries.md b/_es/overviews/parallel-collections/ctries.md
index c45a112520..2432510f03 100644
--- a/_es/overviews/parallel-collections/ctries.md
+++ b/_es/overviews/parallel-collections/ctries.md
@@ -1,9 +1,6 @@
---
layout: multipage-overview
title: Tries Concurrentes
-
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
@@ -163,6 +160,6 @@ en paralelo.
2. [Concurrent Tries with Efficient Non-Blocking Snapshots][2]
3. [Methods of computing square roots][3]
- [1]: http://infoscience.epfl.ch/record/166908/files/ctries-techreport.pdf "Ctries-techreport"
+ [1]: https://infoscience.epfl.ch/record/166908/files/ctries-techreport.pdf "Ctries-techreport"
[2]: http://lampwww.epfl.ch/~prokopec/ctries-snapshot.pdf "Ctries-snapshot"
- [3]: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method "babylonian-method"
+ [3]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method "babylonian-method"
diff --git a/_es/overviews/parallel-collections/custom-parallel-collections.md b/_es/overviews/parallel-collections/custom-parallel-collections.md
index 802d9f5286..d142e88083 100644
--- a/_es/overviews/parallel-collections/custom-parallel-collections.md
+++ b/_es/overviews/parallel-collections/custom-parallel-collections.md
@@ -1,9 +1,6 @@
---
layout: multipage-overview
title: Creating Custom Parallel Collections
-
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
diff --git a/_es/overviews/parallel-collections/overview.md b/_es/overviews/parallel-collections/overview.md
index 8e69d27b2a..41ec0d61a8 100644
--- a/_es/overviews/parallel-collections/overview.md
+++ b/_es/overviews/parallel-collections/overview.md
@@ -1,9 +1,6 @@
---
layout: multipage-overview
title: Overview
-
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
diff --git a/_es/overviews/parallel-collections/performance.md b/_es/overviews/parallel-collections/performance.md
index 26d2237b10..c7de720783 100644
--- a/_es/overviews/parallel-collections/performance.md
+++ b/_es/overviews/parallel-collections/performance.md
@@ -1,9 +1,6 @@
---
layout: multipage-overview
title: Midiendo el rendimiento
-
-discourse: false
-
partof: parallel-collections
overview-name: Parallel Collections
@@ -273,5 +270,5 @@ los que serían requeridos por arrays o vectores).
1. [Anatomy of a flawed microbenchmark, Brian Goetz][1]
2. [Dynamic compilation and performance measurement, Brian Goetz][2]
- [1]: http://www.ibm.com/developerworks/java/library/j-jtp02225/index.html "flawed-benchmark"
- [2]: http://www.ibm.com/developerworks/library/j-jtp12214/ "dynamic-compilation"
+ [1]: https://www.ibm.com/developerworks/java/library/j-jtp02225/index.html "flawed-benchmark"
+ [2]: https://www.ibm.com/developerworks/library/j-jtp12214/ "dynamic-compilation"
diff --git a/_es/tour/abstract-types.md b/_es/tour/abstract-type-members.md
similarity index 70%
rename from _es/tour/abstract-types.md
rename to _es/tour/abstract-type-members.md
index ac54a11ca7..1e9afc50d7 100644
--- a/_es/tour/abstract-types.md
+++ b/_es/tour/abstract-type-members.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Tipos Abstractos
-
-discourse: false
-
partof: scala-tour
num: 2
@@ -17,56 +14,60 @@ previous-page: tour-of-scala
En Scala, las cases son parametrizadas con valores (los parámetros de construcción) y con tipos (si las clases son [genéricas](generic-classes.html)). Por razones de consistencia, no es posible tener solo valores como miembros de objetos; tanto los tipos como los valores son miembros de objetos. Además, ambos tipos de miembros pueden ser concretos y abstractos.
A continuación un ejemplo el cual define de forma conjunta una asignación de valor tardía y un tipo abstracto como miembros del [trait](traits.html) `Buffer`.
- trait Buffer {
- type T
- val element: T
- }
+```scala mdoc
+trait Buffer {
+ type T
+ val element: T
+}
+```
Los *tipos abstractos* son tipos los cuales su identidad no es precisamente conocida. En el ejemplo anterior, lo único que sabemos es que cada objeto de la clase `Buffer` tiene un miembro de tipo `T`, pero la definición de la clase `Buffer` no revela qué tipo concreto se corresponde con el tipo `T`. Tal como las definiciones de valores, es posible sobrescribir las definiciones de tipos en subclases. Esto permite revelar más información acerca de un tipo abstracto al acotar el tipo ligado (el cual describe las posibles instancias concretas del tipo abstracto).
En el siguiente programa derivamos la clase `SeqBuffer` la cual nos permite almacenar solamente sequencias en el buffer al estipular que el tipo `T` tiene que ser un subtipo de `Seq[U]` para un nuevo tipo abstracto `U`:
- abstract class SeqBuffer extends Buffer {
- type U
- type T <: Seq[U]
- def length = element.length
- }
+```scala mdoc
+abstract class SeqBuffer extends Buffer {
+ type U
+ type T <: Seq[U]
+ def length = element.length
+}
+```
Traits o [clases](classes.html) con miembros de tipos abstractos son generalmente usados en combinación con instancias de clases anónimas. Para ilustrar este concepto veremos un programa el cual trata con un buffer de sequencia que se remite a una lista de enteros.
- abstract class IntSeqBuffer extends SeqBuffer {
- type U = Int
- }
-
- object AbstractTypeTest1 extends App {
- def newIntSeqBuf(elem1: Int, elem2: Int): IntSeqBuffer =
- new IntSeqBuffer {
- type T = List[U]
- val element = List(elem1, elem2)
- }
- val buf = newIntSeqBuf(7, 8)
- println("length = " + buf.length)
- println("content = " + buf.element)
- }
+```scala mdoc
+abstract class IntSeqBuffer extends SeqBuffer {
+ type U = Int
+}
+
+def newIntSeqBuf(elem1: Int, elem2: Int): IntSeqBuffer =
+ new IntSeqBuffer {
+ type T = List[U]
+ val element = List(elem1, elem2)
+ }
+val buf = newIntSeqBuf(7, 8)
+println("length = " + buf.length)
+println("content = " + buf.element)
+```
El tipo retornado por el método `newIntSeqBuf` está ligado a la especialización del trait `Buffer` en el cual el tipo `U` es ahora equivalente a `Int`. Existe un tipo alias similar en la instancia de la clase anónima dentro del cuerpo del método `newIntSeqBuf`. En ese lugar se crea una nueva instancia de `IntSeqBuffer` en la cual el tipo `T` está ligado a `List[Int]`.
Es necesario notar que generalmente es posible transformar un tipo abstracto en un tipo paramétrico de una clase y viceversa. A continuación se muestra una versión del código anterior el cual solo usa tipos paramétricos.
- abstract class Buffer[+T] {
- val element: T
- }
- abstract class SeqBuffer[U, +T <: Seq[U]] extends Buffer[T] {
- def length = element.length
- }
- object AbstractTypeTest2 extends App {
- def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] =
- new SeqBuffer[Int, List[Int]] {
- val element = List(e1, e2)
- }
- val buf = newIntSeqBuf(7, 8)
- println("length = " + buf.length)
- println("content = " + buf.element)
- }
+```scala mdoc:reset
+abstract class Buffer[+T] {
+ val element: T
+}
+abstract class SeqBuffer[U, +T <: Seq[U]] extends Buffer[T] {
+ def length = element.length
+}
+def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] =
+ new SeqBuffer[Int, List[Int]] {
+ val element = List(e1, e2)
+ }
+val buf = newIntSeqBuf(7, 8)
+println("length = " + buf.length)
+println("content = " + buf.element)
+```
Nótese que es necesario usar [variance annotations](variances.html) aquí; de otra manera no sería posible ocultar el tipo implementado por la secuencia concreta del objeto retornado por `newIntSeqBuf`. Además, existen casos en los cuales no es posible remplazar tipos abstractos con tipos parametrizados.
diff --git a/_es/tour/annotations.md b/_es/tour/annotations.md
index 490e2287da..37dd912f97 100644
--- a/_es/tour/annotations.md
+++ b/_es/tour/annotations.md
@@ -1,16 +1,13 @@
---
layout: tour
title: Anotaciones
-
-discourse: false
-
partof: scala-tour
num: 3
language: es
-next-page: classes
-previous-page: abstract-types
+next-page: packages-and-imports
+previous-page: abstract-type-members
---
Las anotaciones sirven para asociar meta-información con definiciones.
@@ -23,16 +20,15 @@ El significado de las anotaciones _depende de la implementación_. En la platafo
| Scala | Java |
| ------ | ------ |
-| [`scala.SerialVersionUID`](https://www.scala-lang.org/api/current/scala/SerialVersionUID.html) | [`serialVersionUID`](http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html#navbar_bottom) (campo, variable) |
-| [`scala.deprecated`](https://www.scala-lang.org/api/current/scala/deprecated.html) | [`java.lang.Deprecated`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Deprecated.html) |
+| [`scala.SerialVersionUID`](https://www.scala-lang.org/api/current/scala/SerialVersionUID.html) | [`serialVersionUID`](https://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html#navbar_bottom) (campo, variable) |
+| [`scala.deprecated`](https://www.scala-lang.org/api/current/scala/deprecated.html) | [`java.lang.Deprecated`](https://java.sun.com/j2se/1.5.0/docs/api/java/lang/Deprecated.html) |
| [`scala.inline`](https://www.scala-lang.org/api/current/scala/inline.html) (desde 2.6.0) | sin equivalente |
-| [`scala.native`](https://www.scala-lang.org/api/current/scala/native.html) (desde 2.6.0) | [`native`](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
-| [`scala.remote`](https://www.scala-lang.org/api/current/scala/remote.html) | [`java.rmi.Remote`](http://java.sun.com/j2se/1.5.0/docs/api/java/rmi/Remote.html) |
-| [`scala.throws`](https://www.scala-lang.org/api/current/scala/throws.html) | [`throws`](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
-| [`scala.transient`](https://www.scala-lang.org/api/current/scala/transient.html) | [`transient`](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
+| [`scala.native`](https://www.scala-lang.org/api/current/scala/native.html) (desde 2.6.0) | [`native`](https://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
+| [`scala.throws`](https://www.scala-lang.org/api/current/scala/throws.html) | [`throws`](https://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
+| [`scala.transient`](https://www.scala-lang.org/api/current/scala/transient.html) | [`transient`](https://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
| [`scala.unchecked`](https://www.scala-lang.org/api/current/scala/unchecked.html) (desde 2.4.0) | sin equivalente |
-| [`scala.volatile`](https://www.scala-lang.org/api/current/scala/volatile.html) | [`volatile`](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
-| [`scala.beans.BeanProperty`](https://www.scala-lang.org/api/current/scala/beans/BeanProperty.html) | [`Design pattern`](http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html) |
+| [`scala.volatile`](https://www.scala-lang.org/api/current/scala/volatile.html) | [`volatile`](https://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html) (palabra clave) |
+| [`scala.beans.BeanProperty`](https://www.scala-lang.org/api/current/scala/beans/BeanProperty.html) | [`Design pattern`](https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html) |
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.
@@ -77,7 +73,7 @@ Si comentamos la anotación `throws` en la clase `Reader` se produce el siguient
**Nota:** Asegurate de usar la opción `-target:jvm-1.5` con anotaciones de Java.
-Java 1.5 introdujo metadata definida por el usuario en la forma de [anotaciones](http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html). Una característica fundamental de las anotaciones es que se basan en pares nombre-valor específicos para inicializar sus elementos. Por ejemplo, si necesitamos una anotación para rastrear el código de alguna clase debemos definirlo así:
+Java 1.5 introdujo metadata definida por el usuario en la forma de [anotaciones](https://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html). Una característica fundamental de las anotaciones es que se basan en pares nombre-valor específicos para inicializar sus elementos. Por ejemplo, si necesitamos una anotación para rastrear el código de alguna clase debemos definirlo así:
@interface Source {
public String URL();
@@ -86,13 +82,13 @@ Java 1.5 introdujo metadata definida por el usuario en la forma de [anotaciones]
Y después utilizarlo de la siguiente manera
- @Source(URL = "http://coders.com/",
+ @Source(URL = "https://coders.com/",
mail = "support@coders.com")
public class MyClass extends HisClass ...
Una anotación en Scala se asemeja a una invocación a un constructor. Para instanciar una anotación de Java es necesario usar los argumentos nombrados:
- @Source(URL = "http://coders.com/",
+ @Source(URL = "https://coders.com/",
mail = "support@coders.com")
class MyScalaClass ...
@@ -105,22 +101,22 @@ Esta sintaxis es bastante tediosa si la anotación contiene solo un elemento (si
Y podemos aplicarlo así:
- @SourceURL("http://coders.com/")
+ @SourceURL("https://coders.com/")
public class MyClass extends HisClass ...
En este caso, Scala provee la misma posibilidad:
- @SourceURL("http://coders.com/")
+ @SourceURL("https://coders.com/")
class MyScalaClass ...
El elemento `mail` fue especificado con un valor por defecto (mediante la cláusula `default`) por lo tanto no necesitamos proveer explicitamente un valor para este. De todas maneras, si necesitamos pasarle un valor no podemos mezclar los dos estilos en Java:
- @SourceURL(value = "http://coders.com/",
+ @SourceURL(value = "https://coders.com/",
mail = "support@coders.com")
public class MyClass extends HisClass ...
Scala provee más flexibilidad en este caso:
- @SourceURL("http://coders.com/",
+ @SourceURL("https://coders.com/",
mail = "support@coders.com")
class MyScalaClass ...
diff --git a/_es/tour/automatic-closures.md b/_es/tour/automatic-closures.md
deleted file mode 100644
index a6eba7b6c5..0000000000
--- a/_es/tour/automatic-closures.md
+++ /dev/null
@@ -1,68 +0,0 @@
----
-layout: tour
-title: Construcción de closures automáticas
-
-discourse: false
-
-partof: scala-tour
-
-num: 16
-language: es
-
-next-page: operators
-previous-page: multiple-parameter-lists
----
-
-Scala permite pasar funciones sin parámetros como parámetros de un método. Cuando un método así es invocado, los parámetros reales de la función enviada sin parámetros no son evaluados y una función "nularia" (de aridad cero, 0-aria, o sin parámetros) es pasada en su lugar. Esta función encapsula el comportamiento del parámetro correspondiente (comunmente conocido como "llamada por nombre").
-
-Para aclarar un poco esto aquí se muestra un ejemplo:
-
- object TargetTest1 extends App {
- def whileLoop(cond: => Boolean)(body: => Unit): Unit =
- if (cond) {
- body
- whileLoop(cond)(body)
- }
- var i = 10
- whileLoop (i > 0) {
- println(i)
- i -= 1
- }
- }
-
-La función `whileLoop` recibe dos parámetros `cond` y `body`. Cuando la función es llamada, los parámetros reales no son evaluados en ese momento. Pero cuando los parámetros son utilizados en el cuerpo de la función `whileLoop`, las funciones nularias creadas implícitamente serán evaluadas en su lugar. Así, nuestro método `whileLoop` implementa un bucle tipo Java mediante una implementación recursiva.
-
-Es posible combinar el uso de [operadores de infijo y postfijo (infix/postfix)](operators.html) con este mecanismo para crear declaraciones más complejas (con una sintaxis agradadable).
-
-Aquí mostramos la implementación de una declaración tipo repetir-a-menos-que (repetir el bucle a no ser que se cumpla X condición):
-
- object TargetTest2 extends App {
- 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)
- }
-
-La función `loop` solo acepta el cuerpo de un bucle y retorna una instancia de la clase `LoopUnlessCond` (la cual encapsula el cuerpo del objeto). Es importante notar que en este punto el cuerpo del bucle no ha sido evaluado aún. La clase `LoopUnlessCond` tiene un método `unless` el cual puede ser usado como un *operador de infijo (infix)*. De esta manera podemos lograr una sintaxis muy natural para nuestro nuevo bucle `repetir { a_menos_que ( )`.
-
-A continuación se expone el resultado de la ejecución de `TargetTest2`:
-
- i = 10
- i = 9
- i = 8
- i = 7
- i = 6
- i = 5
- i = 4
- i = 3
- i = 2
- i = 1
diff --git a/_es/tour/basics.md b/_es/tour/basics.md
index bd86428a9b..484470a508 100644
--- a/_es/tour/basics.md
+++ b/_es/tour/basics.md
@@ -1,9 +1,308 @@
---
layout: tour
title: Basics
-
-discourse: false
-
partof: scala-tour
language: es
+
+num: 2
+next-page: unified-types
+previous-page: tour-of-scala
---
+
+En esta página, practicaremos conceptos básicos de Scala.
+
+## Probando Scala en el navegador
+
+Puedes ejecutar Scala en tu navegador con Scastie.
+
+1. Ve a [Scastie](https://scastie.scala-lang.org/).
+2. Escribe `println("Hello, world!")` en el panel a la izquierda.
+3. Presiona el botón "Run". En el panel de la derecha aparecerá el resultado.
+
+Así, de manera fácil y sin preparación, puedes probar fragmentos de código Scala.
+
+## Expresiones
+
+Las expresiones son sentencias computables.
+
+```scala mdoc
+1 + 1
+```
+
+Se puede ver el resultado de evaluar expresiones usando `println`.
+
+```scala mdoc
+println(1) // 1
+println(1 + 1) // 2
+println("Hello!") // Hello!
+println("Hello," + " world!") // Hello, world!
+```
+
+## Valores
+
+Se puede dar un nombre al resultado de una expresión usando la palabra reservada `val`.
+
+```scala mdoc
+val x = 1 + 1
+println(x) // 2
+```
+
+Los resultados con nombre, como `x` en el ejemplo, son llamados valores. Referenciar un valor no lo vuelve a computar.
+
+Los valores no pueden ser reasignados.
+
+```scala mdoc:fail
+x = 3 // This does not compile.
+```
+
+Scala es capaz de inferir el tipo de un valor. Aun así, también se puede indicar el tipo usando una anotación:
+
+```scala mdoc:nest
+val x: Int = 1 + 1
+```
+
+Nótese que la anotación del tipo `Int` sigue al identificador `x` de la variable, separado por dos puntos `:`.
+
+## Variables
+
+Una variable es como un valor, excepto que a una variable se le puede re-asignar un valor después de declararla. Una variable se declara con la palabra reservada `var`.
+
+```scala mdoc:nest
+var x = 1 + 1
+x = 3 // This compiles because "x" is declared with the "var" keyword.
+println(x * x) // 9
+```
+
+Como con los valores, si se quiere se puede especificar el tipo de una variable mutable:
+
+```scala mdoc:nest
+var x: Int = 1 + 1
+```
+
+## Bloques
+
+Se pueden combinar expresiones rodeándolas con `{}` . A esto le llamamos un bloque.
+
+El resultado de la última expresión del bloque es también el resultado total del bloque.
+
+```scala mdoc
+println({
+ val x = 1 + 1
+ x + 1
+}) // 3
+```
+
+## Funciones
+
+Una función es una expresión que acepta parámetros.
+
+Una función se puede declarar anónima, sin nombre. Por ejemplo, ésta es una función que acepta un número entero `x`, y devuelve el resultado de incrementarlo:
+
+```scala mdoc
+(x: Int) => x + 1
+```
+
+La lista de parámetros de la función está a la izquierda de la flecha `=>`, y a su derecha está el cuerpo de la función.
+
+También podemos asignarle un nombre a la función.
+
+```scala mdoc
+val addOne = (x: Int) => x + 1
+println(addOne(1)) // 2
+```
+
+Las funciones pueden tomar varios parámetros.
+
+```scala mdoc
+val add = (x: Int, y: Int) => x + y
+println(add(1, 2)) // 3
+```
+
+O ninguno.
+
+```scala mdoc
+val getTheAnswer = () => 42
+println(getTheAnswer()) // 42
+```
+
+## Métodos
+
+Los métodos se parecen y comportan casi como a las funciones, pero se diferencian en dos aspectos clave:
+
+Un método se define con la palabra reservada `def`, seguida por el nombre del método, la lista de parámetros, el tipo de valores que el método devuelve, y el cuerpo del método.
+
+```scala mdoc:nest
+def add(x: Int, y: Int): Int = x + y
+println(add(1, 2)) // 3
+```
+
+Observe que el tipo de retorno se declara _después_ de la lista de parámetros, y separado con dos puntos, p.ej. `: Int`.
+
+Un método puede tener varias listas de parámetros.
+
+```scala mdoc
+def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier
+println(addThenMultiply(1, 2)(3)) // 9
+```
+
+O ninguna lista de parámetros.
+
+```scala mdoc
+def name: String = System.getProperty("user.name")
+println("Hello, " + name + "!")
+```
+
+Hay otras diferencias, pero para simplificar, podemos pensar que son similares a las funciones.
+
+Los métodos también pueden tener expresiones de varias lineas.
+
+```scala mdoc
+def getSquareString(input: Double): String = {
+ val square = input * input
+ square.toString
+}
+println(getSquareString(2.5)) // 6.25
+```
+
+La ultima expresión en el cuerpo del método es el valor de retorno del mismo.
+(Scala tiene una palabra reservada `return`, pero se usa raramente y no se aconseja usarla)
+
+## Clases
+
+Una clase se define con la palabra reservada `class`, seguida del nombre, y la lista de parámetros del constructor.
+
+```scala mdoc
+class Greeter(prefix: String, suffix: String) {
+ def greet(name: String): Unit =
+ println(prefix + name + suffix)
+}
+```
+
+El método `greet` tiene un tipo de retorno `Unit`, que indica que el método no tiene nada significativo que devolver. Esto es similar al tipo `void` en C, C++, o Java. La diferencia con estos lenguajes es que en Scala toda expresión debe devolver un valor. Por ello, se usa un tipo `Unit` que tiene con un solo valor que se escribe `()` y no lleva información.
+
+Se puede crear una instancia de una clase con la palabra reservada *new*.
+
+```scala mdoc
+val greeter = new Greeter("Hello, ", "!")
+greeter.greet("Scala developer") // Hello, Scala developer!
+```
+
+Las clases se tratan en profundidad [más adelante](classes.html).
+
+## Case Classes
+
+Hay un tipo especial de clases en Scala, las llamadas "case" classes. Por defecto, las instancias de una case class son inmutables, y se comparan con otras solo por los valores que contienen en cada campo.
+Una case class se define con las palabras reservadas `case class`:
+
+```scala mdoc
+case class Point(x: Int, y: Int)
+```
+
+Se puede crear una instancia de una `case class`, sin usar la palabra reservada `new`.
+
+```scala mdoc
+val point = Point(1, 2)
+val anotherPoint = Point(1, 2)
+val yetAnotherPoint = Point(2, 2)
+```
+
+Y son comparadas por valor.
+
+```scala mdoc
+if (point == anotherPoint) {
+ println(s"$point and $anotherPoint are the same.")
+} else {
+ println(s"$point and $anotherPoint are different.")
+} // Point(1,2) and Point(1,2) are the same.
+
+if (point == yetAnotherPoint) {
+ println(s"$point and $yetAnotherPoint are the same.")
+} else {
+ println(s"$point and $yetAnotherPoint are different.")
+} // Point(1,2) and Point(2,2) are different.
+```
+
+Hay mucho más sobre las case classes que queremos presentar, y estamos convencidos de que te vas a enamorar de ellas. Se tratan con más detalle [mas adelante](case-classes.html).
+
+## Objetos
+
+Los objetos son instancias de una sola clase de su propia definición. Puedes pensar en ellos como _singleton_ de sus propias clases.
+
+Un objeto se define usando la palabra reservada `object`.
+
+```scala mdoc
+object IdFactory {
+ private var counter = 0
+ def create(): Int = {
+ counter += 1
+ counter
+ }
+}
+```
+
+Para acceder al objeto, lo referencias por su nombre.
+
+```scala mdoc
+val newId: Int = IdFactory.create()
+println(newId) // 1
+val newerId: Int = IdFactory.create()
+println(newerId) // 2
+```
+
+Cubriremos los objetos en profundidad [más adelante](singleton-objects.html).
+
+## Traits
+
+Los traits son tipos que contienen campos y métodos. Se pueden combinar múltiples traits.
+
+Un trait se define usando la palabra reservada `trait`.
+
+```scala mdoc:nest
+trait Greeter {
+ def greet(name: String): Unit
+}
+```
+
+Un `trait` también puede definir un método, o un valor, con una implementación por defecto.
+
+```scala mdoc:reset
+trait Greeter {
+ def greet(name: String): Unit =
+ println("Hello, " + name + "!")
+}
+```
+
+Un `trait` también puede extender otros traits, usando la palabra clave `extends`. Asimismo, en un `trait` se puede redefinir la implementación de un método heredado, usando la palabra reservada `override`.
+
+```scala mdoc
+class DefaultGreeter extends Greeter
+
+class CustomizableGreeter(prefix: String, postfix: String) extends Greeter {
+ override def greet(name: String): Unit = {
+ println(prefix + name + postfix)
+ }
+}
+
+val greeter = new DefaultGreeter()
+greeter.greet("Scala developer") // Hello, Scala developer!
+
+val customGreeter = new CustomizableGreeter("How are you, ", "?")
+customGreeter.greet("Scala developer") // How are you, Scala developer?
+```
+
+Aquí, `DefaultGreeter` extiende un solo trait, pero puede extender múltiples traits.
+
+Los `traits` se tratan con detalle [en otra página](traits.html).
+
+## Método principal (Main Method)
+
+El método principal (main) es el punto donde comienza la ejecución de un programa en Scala. La máquina virtual de java (_Java Virtual Machine_ or JVM) requiere, para ejecutar un código Scala, que éste tenga un método principal llamado `main` cuyo único parámetro sea un arrray de Strings.
+
+Usando un objeto, puedes definir el método principal de la siguiente forma:
+
+```scala mdoc
+object Main {
+ def main(args: Array[String]): Unit =
+ println("Hello, Scala developer!")
+}
+```
diff --git a/_es/tour/by-name-parameters.md b/_es/tour/by-name-parameters.md
index da953ddcb4..24f1e0cd23 100644
--- a/_es/tour/by-name-parameters.md
+++ b/_es/tour/by-name-parameters.md
@@ -1,9 +1,6 @@
---
layout: tour
title: By-name Parameters
-
-discourse: false
-
partof: scala-tour
language: es
---
diff --git a/_es/tour/case-classes.md b/_es/tour/case-classes.md
index 4e4a203b20..7a4989bde5 100644
--- a/_es/tour/case-classes.md
+++ b/_es/tour/case-classes.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Clases Case
-
-discourse: false
-
partof: scala-tour
num: 5
@@ -13,7 +10,7 @@ next-page: compound-types
previous-page: classes
---
-Scala da soporte a la noción de _clases caso_ (en inglés _case classes_, desde ahora _clases Case_). Las clases Case son clases regulares las cuales exportan sus parámetros constructores y a su vez proveen una descomposición recursiva de sí mismas a través de [reconocimiento de patrones](pattern-matching.html).
+Scala da soporte a la noción de _clases case_ (en inglés _case classes_, desde ahora _clases Case_). Las clases Case son clases regulares las cuales exportan sus parámetros constructores y a su vez proveen una descomposición recursiva de sí mismas a través de [reconocimiento de patrones](pattern-matching.html).
A continuación se muestra un ejemplo para una jerarquía de clases la cual consiste de una super clase abstracta llamada `Term` y tres clases concretas: `Var`, `Fun` y `App`.
@@ -22,7 +19,7 @@ A continuación se muestra un ejemplo para una jerarquía de clases la cual cons
case class Fun(arg: String, body: Term) extends Term
case class App(f: Term, v: Term) extends Term
-Esta jerarquía de clases puede ser usada para representar términos de [cálculo lambda no tipado](http://www.ezresult.com/article/Lambda_calculus). Para facilitar la construcción de instancias de clases Case, Scala no requiere que se utilice la primitiva `new`. Simplemente es posible utilizar el nombre de la clase como una llamada a una función.
+Esta jerarquía de clases puede ser usada para representar términos de [cálculo lambda no tipado](https://es.wikipedia.org/wiki/C%C3%A1lculo_lambda). Para facilitar la construcción de instancias de clases Case, Scala no requiere que se utilice la primitiva `new`. Simplemente es posible utilizar el nombre de la clase como una llamada a una función.
Aquí un ejemplo:
@@ -76,6 +73,8 @@ Solo tiene sentido definir una clase Case si el reconocimiento de patrones es us
println(isIdentityFun(t))
}
-En nuestro ejemplo, la función `printTerm` es expresada como una sentencia basada en reconocimiento de patrones, la cual comienza con la palabra reservada `match` y consiste en secuencias de sentencias tipo `case PatronBuscado => Código que se ejecuta`.
+En nuestro ejemplo, la función `printTerm` es expresada como una sentencia basada en reconocimiento de patrones, la cual comienza con la palabra reservada `match` y consiste en secuencias de sentencias tipo `case PatrónBuscado => Código que se ejecuta`.
-El programa de arriba también define una función `isIdentityFun` la cual comprueba si un término dado se corresponde con una función identidad simple. Ese ejemplo utiliza patrones y guardas más avanzados (obsrvese la guarda `if x==y`). Tras reconocer un patrón con un valor dado, la guarda (definida después de la palabra clave `if`) es evaluada. Si retorna `true` (verdadero), el reconocimiento es exitoso; de no ser así, falla y se intenta con el siguiente patrón.
+El programa de arriba también define una función `isIdentityFun` la cual comprueba si un término dado se corresponde con una función identidad simple. Ese ejemplo utiliza patrones y comparaciones más avanzadas (obsérvese la guarda `if x==y`).
+Tras reconocer un patrón con un valor dado, se evalúa la comparación (definida después de la palabra clave `if`).
+Si retorna `true` (verdadero), el reconocimiento es exitoso; de no ser así, falla y se intenta con el siguiente patrón.
diff --git a/_es/tour/classes.md b/_es/tour/classes.md
index 1ed2c731dc..3f3939b3bc 100644
--- a/_es/tour/classes.md
+++ b/_es/tour/classes.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Clases
-
-discourse: false
-
partof: scala-tour
num: 4
@@ -32,7 +29,7 @@ Las clases en Scala son parametrizadas con argumentos constructores (inicializad
Para instanciar una clase es necesario usar la primitiva `new`, como se muestra en el siguiente ejemplo:
object Classes {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val pt = new Point(1, 2)
println(pt)
pt.move(10, 10)
diff --git a/_es/tour/compound-types.md b/_es/tour/compound-types.md
index a60e7b54b5..9173b7ff1c 100644
--- a/_es/tour/compound-types.md
+++ b/_es/tour/compound-types.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Tipos Compuestos
-
-discourse: false
-
partof: scala-tour
num: 6
@@ -44,4 +41,4 @@ Los tipos compuestos pueden crearse a partir de varios tipos de objeto y pueden
La forma general es: `A with B with C ... { refinamiento }`
-Un ejemplo del uso de los refinamientos se muestra en la página sobre [tipos abstractos](abstract-types.html).
+Un ejemplo del uso de los refinamientos se muestra en la página sobre [tipos abstractos](abstract-type-members.html).
diff --git a/_es/tour/default-parameter-values.md b/_es/tour/default-parameter-values.md
index 4a34538fce..f4fe5322f2 100644
--- a/_es/tour/default-parameter-values.md
+++ b/_es/tour/default-parameter-values.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Valores de parámetros por defecto
-
-discourse: false
-
partof: scala-tour
num: 34
@@ -66,4 +63,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-arguments.html).
+Nótese cómo podemos sacar ventaja de cualquier valor por defecto al utilizar [parámetros nombrados]({{ site.baseurl }}/es/tour/named-arguments.html).
diff --git a/_es/tour/extractor-objects.md b/_es/tour/extractor-objects.md
index 5f1d180488..a59c93558a 100644
--- a/_es/tour/extractor-objects.md
+++ b/_es/tour/extractor-objects.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Objetos Extractores
-
-discourse: false
-
partof: scala-tour
num: 8
diff --git a/_es/tour/for-comprehensions.md b/_es/tour/for-comprehensions.md
index 55903d9f1b..55f16ee7d6 100644
--- a/_es/tour/for-comprehensions.md
+++ b/_es/tour/for-comprehensions.md
@@ -1,9 +1,6 @@
---
layout: tour
title: For Comprehensions
-
-discourse: false
-
partof: scala-tour
language: es
---
diff --git a/_es/tour/generic-classes.md b/_es/tour/generic-classes.md
index 5236628353..b89b603ae3 100644
--- a/_es/tour/generic-classes.md
+++ b/_es/tour/generic-classes.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Clases genéricas
-
-discourse: false
-
partof: scala-tour
num: 9
@@ -17,12 +14,15 @@ Tal como en Java 5, Scala provee soporte nativo para clases parametrizados con t
A continuación se muestra un ejemplo:
- class Stack[T] {
- var elems: List[T] = Nil
- def push(x: T) { elems = x :: elems }
- def top: T = elems.head
- def pop() { elems = elems.tail }
- }
+```scala mdoc
+class Stack[T] {
+ var elems: List[T] = Nil
+ def push(x: T): Unit =
+ elems = x :: elems
+ def top: T = elems.head
+ def pop(): Unit = { elems = elems.tail }
+}
+```
La clase `Stack` modela una pila mutable que contiene elementos de un tipo arbitrario `T` (se dice, "una pila de elementos `T`). Los parámetros de tipos nos aseguran que solo elementos legales (o sea, del tipo `T`) sean insertados en la pila (apilados). De forma similar, con los parámetros de tipo podemos expresar que el método `top` solo devolverá elementos de un tipo dado (en este caso `T`).
diff --git a/_es/tour/higher-order-functions.md b/_es/tour/higher-order-functions.md
index 899dca2139..c9e0a9e44b 100644
--- a/_es/tour/higher-order-functions.md
+++ b/_es/tour/higher-order-functions.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Funciones de orden superior
-
-discourse: false
-
partof: scala-tour
num: 18
diff --git a/_es/tour/implicit-conversions.md b/_es/tour/implicit-conversions.md
index 1979510108..a0e254a3ca 100644
--- a/_es/tour/implicit-conversions.md
+++ b/_es/tour/implicit-conversions.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Implicit Conversions
-
-discourse: false
-
partof: scala-tour
num: 32
diff --git a/_es/tour/implicit-parameters.md b/_es/tour/implicit-parameters.md
index 581593a7c3..f6c52d5c8a 100644
--- a/_es/tour/implicit-parameters.md
+++ b/_es/tour/implicit-parameters.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Parámetros implícitos
-
-discourse: false
-
partof: scala-tour
num: 10
diff --git a/_es/tour/inner-classes.md b/_es/tour/inner-classes.md
index c072021dc8..9b04862d27 100644
--- a/_es/tour/inner-classes.md
+++ b/_es/tour/inner-classes.md
@@ -1,58 +1,61 @@
---
layout: tour
title: Clases Internas
-
-discourse: false
-
partof: scala-tour
num: 11
language: es
-next-page: mixin-class-composition
+next-page: tuples
previous-page: implicit-parameters
---
En Scala es posible que las clases tengan como miembro otras clases. A diferencia de lenguajes similares a Java donde ese tipo de clases internas son miembros de las clases que las envuelven, en Scala esas clases internas están ligadas al objeto externo. Para ilustrar esta diferencia, vamos a mostrar rápidamente una implementación del tipo grafo:
- class Graph {
- class Node {
- var connectedNodes: List[Node] = Nil
- def connectTo(node: Node) {
- if (connectedNodes.find(node.equals).isEmpty) {
- connectedNodes = node :: connectedNodes
- }
- }
- }
- var nodes: List[Node] = Nil
- def newNode: Node = {
- val res = new Node
- nodes = res :: nodes
- res
+```scala mdoc
+class Graph {
+ class Node {
+ var connectedNodes: List[Node] = Nil
+ def connectTo(node: Node): Unit = {
+ if (!connectedNodes.exists(node.equals)) {
+ connectedNodes = node :: connectedNodes
}
}
+ }
+ var nodes: List[Node] = Nil
+ def newNode: Node = {
+ val res = new Node
+ nodes = res :: nodes
+ res
+ }
+}
+```
En nuestro programa, los grafos son representados mediante una lista de nodos. Estos nodos son objetos de la clase interna `Node`. Cada nodo tiene una lista de vecinos que se almacena en la lista `connectedNodes`. Ahora podemos crear un grafo con algunos nodos y conectarlos incrementalmente:
- object GraphTest extends App {
- val g = new Graph
- val n1 = g.newNode
- val n2 = g.newNode
- val n3 = g.newNode
- n1.connectTo(n2)
- n3.connectTo(n1)
- }
+```scala mdoc:nest
+def graphTest: Unit = {
+ val g = new Graph
+ val n1 = g.newNode
+ val n2 = g.newNode
+ val n3 = g.newNode
+ n1.connectTo(n2)
+ n3.connectTo(n1)
+}
+```
Ahora vamos a completar el ejemplo con información relacionada al tipado para definir explicitamente de qué tipo son las entidades anteriormente definidas:
- object GraphTest extends App {
- val g: Graph = new Graph
- val n1: g.Node = g.newNode
- val n2: g.Node = g.newNode
- val n3: g.Node = g.newNode
- n1.connectTo(n2)
- n3.connectTo(n1)
- }
+```scala mdoc:nest
+def graphTest: Unit = {
+ val g: Graph = new Graph
+ val n1: g.Node = g.newNode
+ val n2: g.Node = g.newNode
+ val n3: g.Node = g.newNode
+ n1.connectTo(n2)
+ n3.connectTo(n1)
+}
+```
El código anterior muestra que al tipo del nodo le es prefijado con la instancia superior (que en nuestro ejemplo es `g`). Si ahora tenemos dos grafos, el sistema de tipado de Scala no nos permite mezclar nodos definidos en un grafo con nodos definidos en otro, ya que los nodos del otro grafo tienen un tipo diferente.
@@ -73,8 +76,8 @@ Por favor note que en Java la última linea del ejemplo anterior hubiese sido co
class Graph {
class Node {
var connectedNodes: List[Graph#Node] = Nil // Graph#Node en lugar de Node
- def connectTo(node: Graph#Node) {
- if (connectedNodes.find(node.equals).isEmpty) {
+ def connectTo(node: Graph#Node): Unit = {
+ if (!connectedNodes.exists(node.equals)) {
connectedNodes = node :: connectedNodes
}
}
diff --git a/_es/tour/lower-type-bounds.md b/_es/tour/lower-type-bounds.md
index 0fc3b5aba5..1ba22280af 100644
--- a/_es/tour/lower-type-bounds.md
+++ b/_es/tour/lower-type-bounds.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Límite de tipado inferior
-
-discourse: false
-
partof: scala-tour
num: 26
diff --git a/_es/tour/mixin-class-composition.md b/_es/tour/mixin-class-composition.md
index 6343e0a7c6..bd53274158 100644
--- a/_es/tour/mixin-class-composition.md
+++ b/_es/tour/mixin-class-composition.md
@@ -1,16 +1,13 @@
---
layout: tour
title: Composición de clases mixin
-
-discourse: false
-
partof: scala-tour
num: 12
language: es
next-page: singleton-objects
-previous-page: inner-classes
+previous-page: tuples
---
_Nota de traducción: La palabra `mixin` puede ser traducida como mezcla, dando título a esta sección de: Composición de clases Mezcla, pero es preferible utilizar la notación original_
@@ -25,7 +22,7 @@ A diferencia de lenguajes que solo soportan _herencia simple_, Scala tiene una n
A continuación, considere una clase mezcla la cual extiende `AbsIterator` con un método `foreach` el cual aplica una función dada a cada elemento retornado por el iterador. Para definir una clase que puede usarse como una clase mezcla usamos la palabra clave `trait`.
trait RichIterator extends AbsIterator {
- def foreach(f: T => Unit) { while (hasNext) f(next()) }
+ def foreach(f: T => Unit): Unit = { while (hasNext) f(next()) }
}
Aquí se muestra una clase iterador concreta, la cual retorna caracteres sucesivos de una cadena de caracteres dada:
@@ -40,7 +37,7 @@ Aquí se muestra una clase iterador concreta, la cual retorna caracteres sucesiv
Nos gustaría combinar la funcionalidad de `StringIterator` y `RichIterator` en una sola clase. Solo con herencia simple e interfaces esto es imposible, ya que ambas clases contienen implementaciones para sus miembros. Scala nos ayuda con sus _compisiciones de clases mezcladas_. Permite a los programadores reutilizar el delta de la definición de una clase, esto es, todas las nuevas definiciones que no son heredadas. Este mecanismo hace posible combinar `StringIterator` con `RichIterator`, como es hecho en el siguiente programa, el cual imprime una columna de todos los caracteres de una cadena de caracteres dada.
object StringIteratorTest {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
class Iter extends StringIterator("Scala") with RichIterator
val iter = new Iter
iter foreach println
diff --git a/_es/tour/multiple-parameter-lists.md b/_es/tour/multiple-parameter-lists.md
index 9eff54f5b1..83b7218c0b 100644
--- a/_es/tour/multiple-parameter-lists.md
+++ b/_es/tour/multiple-parameter-lists.md
@@ -1,24 +1,41 @@
---
layout: tour
title: Currying
-
-discourse: false
-
partof: scala-tour
num: 15
language: es
-next-page: automatic-closures
+next-page: operators
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._
+_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. Entiéndase 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._
Los métodos pueden definir múltiples listas de parámetros. Cuando un método es invocado con un número menor de listas de parámetros, en su lugar se devolverá una función que toma las listas faltantes como sus argumentos.
-Aquí se muestra un ejemplo:
+### Ejemplos
+
+A continuación hay un ejemplo, tal y como se define en el trait `TraversableOnce` en el API de colecciones de Scala:
+
+```scala mdoc:fail
+def foldLeft[B](z: B)(op: (B, A) => B): B
+```
+
+`foldLeft` aplica una función (que recibe dos parámetros) `op` a un valor inicial `z` y todos los elementos de esta colección, de izquierda a derecha. A continuación se muestra un ejemplo de su uso.
+
+Comenzando con un valor inicial 0, `foldLeft` aplica la función `(m, n) => m + n` a cada uno de los elementos de la lista y al valor acumulado previo.
+
+```scala mdoc
+val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+val res = numbers.foldLeft(0)((m, n) => m + n)
+println(res) // 55
+```
+
+A continuación se muestra otro ejemplo:
+
+```scala mdoc
object CurryTest extends App {
def filter(xs: List[Int], p: Int => Boolean): List[Int] =
@@ -32,10 +49,78 @@ Aquí se muestra un ejemplo:
println(filter(nums, modN(2)))
println(filter(nums, modN(3)))
}
+```
-_Nota: el método `modN` está parcialmente aplicado en las dos llamadas a `filter`; esto significa que solo su primer argumento es realmente aplicado. El término `modN(2)` devuelve una función de tipo `Int => Boolean` y es por eso un posible candidato para el segundo argumento de la función `filter`_
+_Nota: el método `modN` está parcialmente aplicado en las dos llamadas a `filter`; esto significa que solo su primer argumento es realmente aplicado. El término `modN(2)` devuelve una función de tipo `Int => Boolean` y es por eso un posible candidato para el segundo argumento de la función `filter`._
Aquí se muestra la salida del programa anterior:
- List(2,4,6,8)
- List(3,6)
+```scala mdoc
+List(2,4,6,8)
+List(3,6)
+```
+
+### Casos de uso
+
+Casos de uso sugeridos para múltiples listas de parámetros incluyen:
+
+#### Inferencia de tipos
+
+En Scala, la inferencia de tipos se realiza parámetro a parámetro.
+Suponer que se dispone del siguiente método:
+
+```scala mdoc
+def foldLeft1[A, B](as: List[A], b0: B, op: (B, A) => B) = ???
+```
+
+Si se invoca de la siguiente manera, se puede comprobar que no compila correctamente:
+
+```scala mdoc:fail
+def notPossible = foldLeft1(numbers, 0, _ + _)
+```
+
+Debes invocarlo de alguna de las maneras propuestas a continuación:
+
+```scala mdoc
+def firstWay = foldLeft1[Int, Int](numbers, 0, _ + _)
+def secondWay = foldLeft1(numbers, 0, (a: Int, b: Int) => a + b)
+```
+
+Esto se debe a que Scala no será capaz de inferir el tipo de la función `_ + _`, como está aún infiriendo `A` y `B`.
+Moviéndo el parámetro `op` a su propia lista de parámetros, los tipos de `A` y `B` son inferidos en la primera lista de parámetros.
+Una vez se han inferido sus tipos, estos están disponibles para la segunda lista de parámetros y `_ + _ ` podrá casar con los tipos inferidos `(Int, Int) => Int`
+
+```scala mdoc
+def foldLeft2[A, B](as: List[A], b0: B)(op: (B, A) => B) = ???
+def possible = foldLeft2(numbers, 0)(_ + _)
+```
+
+Esta definición no necesita de ninguna pista adicional y puede inferir todos los tipos de los parámetros.
+
+
+#### Parámetros implícitos
+
+Para especificar solamente ciertos parámetros como [`implicit`](https://docs.scala-lang.org/tour/implicit-parameters.html), ellos deben ser colocados en su propia lista de parámetros implícitos (`implicit`).
+
+Un ejemplo de esto se muestra a continuación:
+
+```scala mdoc
+def execute(arg: Int)(implicit ec: scala.concurrent.ExecutionContext) = ???
+```
+
+#### Aplicación parcial
+
+Cuando un método es invocado con menos parámetros que los que están declarados en la definición del método, esto generará una función que toma los parámetros faltantes como argumentos. Esto se conoce formalmente como [aplicación parcial](https://en.wikipedia.org/wiki/Partial_application).
+
+Por ejemplo,
+
+```scala mdoc:nest
+val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+val numberFunc = numbers.foldLeft(List[Int]()) _
+
+val squares = numberFunc((xs, x) => xs :+ x*x)
+println(squares) // List(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
+
+val cubes = numberFunc((xs, x) => xs :+ x*x*x)
+println(cubes) // List(1, 8, 27, 64, 125, 216, 343, 512, 729, 1000)
+```
diff --git a/_es/tour/named-arguments.md b/_es/tour/named-arguments.md
index ab289648a7..fe38fe15d4 100644
--- a/_es/tour/named-arguments.md
+++ b/_es/tour/named-arguments.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Parámetros nombrados
-
-discourse: false
-
partof: scala-tour
num: 35
@@ -14,24 +11,24 @@ previous-page: default-parameter-values
En la invocación de métodos y funciones se puede usar el nombre de las variables explícitamente en la llamada, de la siguiente manera:
- def imprimirNombre(nombre:String, apellido:String) = {
+ def imprimirNombre(nombre: String, apellido: String) = {
println(nombre + " " + apellido)
}
imprimirNombre("John","Smith")
// Imprime "John Smith"
- imprimirNombre(first = "John",last = "Smith")
+ imprimirNombre(nombre = "John", apellido = "Smith")
// Imprime "John Smith"
- imprimirNombre(last = "Smith",first = "John")
+ imprimirNombre(apellido = "Smith", nombre = "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:
- def imprimirNombre(nombre:String = "John", apellido:String = "Smith") = {
+ def imprimirNombre(nombre: String = "John", apellido: String = "Smith") = {
println(nombre + " " + apellido)
}
- printName(apellido = "Jones")
+ imprimirNombre(apellido = "Jones")
// Imprime "John Jones"
language: es
diff --git a/_es/tour/nested-functions.md b/_es/tour/nested-functions.md
index 3813a2b905..2e77eb4ea4 100644
--- a/_es/tour/nested-functions.md
+++ b/_es/tour/nested-functions.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Funciones Anidadas
-
-discourse: false
-
partof: scala-tour
num: 13
diff --git a/_es/tour/operators.md b/_es/tour/operators.md
index fa7c55cf65..6aeb98e046 100644
--- a/_es/tour/operators.md
+++ b/_es/tour/operators.md
@@ -1,16 +1,13 @@
---
layout: tour
title: Operadores
-
-discourse: false
-
partof: scala-tour
num: 17
language: es
next-page: higher-order-functions
-previous-page: automatic-closures
+previous-page: multiple-parameter-lists
---
En Scala, cualquier método el cual reciba un solo parámetro puede ser usado como un *operador de infijo (infix)*. Aquí se muestra la definición de la clase `MyBool`, la cual define tres métodos `and`, `or`, y `negate`.
diff --git a/_es/tour/package-objects.md b/_es/tour/package-objects.md
new file mode 100644
index 0000000000..3878959d9e
--- /dev/null
+++ b/_es/tour/package-objects.md
@@ -0,0 +1,14 @@
+---
+layout: tour
+title: Package Objects
+language: es
+partof: scala-tour
+
+num: 36
+previous-page: packages-and-imports
+---
+
+# Package objects
+
+(this section of the tour has not been translated yet. pull request
+with translation welcome!)
diff --git a/_es/tour/packages-and-imports.md b/_es/tour/packages-and-imports.md
index 6f1e51d951..d65092cb46 100644
--- a/_es/tour/packages-and-imports.md
+++ b/_es/tour/packages-and-imports.md
@@ -2,14 +2,11 @@
layout: tour
title: Packages and Imports
language: es
-
-discourse: true
-
partof: scala-tour
num: 35
previous-page: named-arguments
-next-page: type-inference
+next-page: package-objects
---
# Packages and Imports
diff --git a/_es/tour/pattern-matching.md b/_es/tour/pattern-matching.md
index d20d83bf56..40e733df7a 100644
--- a/_es/tour/pattern-matching.md
+++ b/_es/tour/pattern-matching.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Reconocimiento de patrones
-
-discourse: false
-
partof: scala-tour
num: 20
diff --git a/_es/tour/polymorphic-methods.md b/_es/tour/polymorphic-methods.md
index c14ca2a18d..ec656e9f8b 100644
--- a/_es/tour/polymorphic-methods.md
+++ b/_es/tour/polymorphic-methods.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Métodos polimórficos
-
-discourse: false
-
partof: scala-tour
num: 21
diff --git a/_es/tour/regular-expression-patterns.md b/_es/tour/regular-expression-patterns.md
index bb0571a27a..7631ce9397 100644
--- a/_es/tour/regular-expression-patterns.md
+++ b/_es/tour/regular-expression-patterns.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Patrones basados en expresiones regulares
-
-discourse: false
-
partof: scala-tour
num: 22
diff --git a/_es/tour/self-types.md b/_es/tour/self-types.md
index fa430d4887..df02b7dc0a 100644
--- a/_es/tour/self-types.md
+++ b/_es/tour/self-types.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Autorefrencias explicitamente tipadas
-
-discourse: false
-
partof: scala-tour
num: 27
@@ -28,7 +25,7 @@ Aquí hay una definición que sirve para describir un grafo:
def agregarNodo: Nodo
}
-Los grafos consisten de una lista de nodos y vértices (o aristas en alguna bibliografía) donde tanto el tipo nodo, como el vértice fueron declarados abstractos. El uso de [tipos abstractos](abstract-types.html) permite las implementaciones del trait `Grafo` proveer sus propias clases concretas para nodos y vértices. Además, existe un método `agregarNodo` para agregar nuevos nodos al grafo. Los nodos se conectan entre sí utilizando el método `conectarCon`.
+Los grafos consisten de una lista de nodos y vértices (o aristas en alguna bibliografía) donde tanto el tipo nodo, como el vértice fueron declarados abstractos. El uso de [tipos abstractos](abstract-type-members.html) permite las implementaciones del trait `Grafo` proveer sus propias clases concretas para nodos y vértices. Además, existe un método `agregarNodo` para agregar nuevos nodos al grafo. Los nodos se conectan entre sí utilizando el método `conectarCon`.
Una posible implementación de la clase `Grafo`es dada en el siguiente programa:
@@ -94,7 +91,7 @@ Por favor nótese que en esta clase nos es posible instanciar `NodoImpl` porque
Aquí hay un ejemplo de uso de la clase `GrafoDirigidoConcreto`:
- object GraphTest extends App {
+ def graphTest: Unit = {
val g: Grafo = new GrafoDirigidoConcreto
val n1 = g.agregarNodo
val n2 = g.agregarNodo
diff --git a/_es/tour/singleton-objects.md b/_es/tour/singleton-objects.md
index 021b413912..dceed2d7ad 100644
--- a/_es/tour/singleton-objects.md
+++ b/_es/tour/singleton-objects.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Singleton Objects
-
-discourse: false
-
partof: scala-tour
num: 12
@@ -25,11 +22,11 @@ Este método `sum` está disponible de manera global, y puede ser referenciado,
Los objetos singleton son una especie de mezcla entre la definición de una clase de utilización única, la cual no pueden ser instanciada directamente, y un miembro `val`. De hecho, de la misma menera que los `val`, los objetos singleton pueden ser definidos como miembros de un [trait](traits.html) o de una clase, aunque esto no es muy frecuente.
-Un objeto singleton puede extender clases y _traits_. De hecho, una [clase Case](case-classes.html) sin [parámetros de tipo](generic-classes.html) generará por defecto un objeto singleton del mismo nombre, con una [`Función*`](http://www.scala-lang.org/api/current/scala/Function1.html) trait implementada.
+Un objeto singleton puede extender clases y _traits_. De hecho, una [clase Case](case-classes.html) sin [parámetros de tipo](generic-classes.html) generará por defecto un objeto singleton del mismo nombre, con una [`Función*`](https://www.scala-lang.org/api/current/scala/Function1.html) trait implementada.
## Acompañantes ##
-La mayoría de los objetos singleton no están solos, sino que en realidad están asociados con clases del mismo nombre. El "objeto singleton del mismo nombre" de una case Case, mencionada anteriormente es un ejemplo de esto. Cuando esto sucede, el objeto singleton es llamado el *objeto acompañante* de la clase, y la clase es a su vez llamada la *clase acompañante* del objeto.
+La mayoría de los objetos singleton no están solos, sino que en realidad están asociados con clases del mismo nombre. El "objeto singleton del mismo nombre" de una clase Case, mencionada anteriormente es un ejemplo de esto. Cuando esto sucede, el objeto singleton es llamado el *objeto acompañante* de la clase, y la clase es a su vez llamada la *clase acompañante* del objeto.
[Scaladoc](/style/scaladoc.html) proporciona un soporte especial para ir y venir entre una clase y su acompañante: Si el gran círculo conteniendo la “C” u la “O” tiene su borde inferior doblado hacia adentro, es posible hacer click en el círculo para ir a su acompañante.
diff --git a/_es/tour/tour-of-scala.md b/_es/tour/tour-of-scala.md
index e9c26f9e58..b742b271ab 100644
--- a/_es/tour/tour-of-scala.md
+++ b/_es/tour/tour-of-scala.md
@@ -1,48 +1,54 @@
---
layout: tour
title: Introducción
-
-discourse: false
-
partof: scala-tour
num: 1
language: es
-next-page: abstract-types
+next-page: basics
+
---
-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 un lenguaje de programación moderno multi-paradigma diseñado para expresar patrones de programación comunes de una forma concisa, elegante, y con 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. 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. 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](multiple-parameter-lists.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 orden superior](higher-order-functions.html), permite funciones [anidadas](nested-functions.html), y soporta [currying](multiple-parameter-lists.html). Las [clases Case](case-classes.html) de Scala y las construcciones incorporadas al lenguaje para [reconocimiento de patrones](pattern-matching.html) modelan tipos algebraicos 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 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.
+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, la compresión de bucles `for` resultan útiles para formular consultas. Estas características hacen a Scala un lenguaje 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:
* [Clases genéricas](generic-classes.html)
* [anotaciones variables](variances.html),
* 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,
+* [clases internas](inner-classes.html) y [tipos abstractos](abstract-type-members.html) como miembros de objetos,
* [tipos compuestos](compound-types.html)
* [auto-referencias explicitamente tipadas](self-types.html)
* [implicit conversions](implicit-conversions.html)
* [métodos polimórficos](polymorphic-methods.html)
-El [mecanismo de inferencia de tipos locales](type-inference.html) se encarga de que el usuario no tengan que anotar el programa con información redundante de tipado. Combinadas, estas características proveen una base poderosa para el reuso seguro de abstracciones de programación y para la extensión segura (en cuanto a tipos) de software.
+El [mecanismo de inferencia de tipos locales](type-inference.html) se encarga de que el usuario no tenga que anotar el programa con información redundante de tipado. Combinadas, estas características proveen una base poderosa para la reutilización segura de abstracciones de programación y para la extensión segura (en cuanto a tipos) de software.
## Scala es extensible ##
-En la práctica el desarrollo de aplicaciones específicas para un dominio generalmente requiere de "Lenguajes de dominio específico" (DSL). Scala provee una única combinación de mecanismos del lenguaje que simplifican la creación de construcciones propias del lenguaje en forma de librerías:
+En la práctica, el desarrollo de aplicaciones específicas para un dominio generalmente requiere de "Lenguajes de dominio específico" (DSL). Scala provee una única combinación de mecanismos del lenguaje que simplifican la creación de construcciones propias del lenguaje en forma de bibliotecas:
* cualquier método puede ser usado como un operador de [infijo o postfijo](operators.html)
-* [las closures son construidas automáticamente dependiendo del tipo esperado](automatic-closures.html) (tipos objetivo).
El uso conjunto de ambas características facilita la definición de nuevas sentencias sin tener que extender la sintaxis y sin usar facciones de meta-programación como tipo macros.
-Scala está diseñado para interoperar bien con el popular Entorno de ejecución de Java 2 (JRE). En particular, la interacción con el lenguaje orientado a objetos Java es muy sencillo. Scala tiene el mismo esquema de compilación (compilación separada, carga de clases dinámica) que java y permite acceder a las miles de librerías de gran calidad existentes.
+## Scala interopera
+
+Scala está diseñado para interoperar correctamente con la popular Java Runtime Environment (JRE).
+En particular, es posible la misma interacción con el lenguaje de programación Java.
+Nuevas características de Java como SAMs, [lambdas](higher-order-functions.html), [anotaciones](annotations.html), y [clases genéricas](generic-classes.html) tienen sus análogos en Scala.
+
+Aquellas características de Scala que no tienen analogías en Java, como por ejemplo [parámetros por defecto](default-parameter-values.html) y [parámetros con nombre](named-arguments.html), compilan de una forma tan similar a Java como es razonablemente posible.
+Scala tiene el mismo modelo de compilación (compilación separada, carga de clases dinámica) que Java y permite acceder a miles de bibliotecas de alta calidad ya existentes.
+
+## ¡Disfruta el tour!
Por favor continúe a la próxima página para conocer más.
diff --git a/_es/tour/traits.md b/_es/tour/traits.md
index 363fee8148..6c41030de5 100644
--- a/_es/tour/traits.md
+++ b/_es/tour/traits.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Traits
-
-discourse: false
-
partof: scala-tour
num: 24
diff --git a/_es/tour/tuples.md b/_es/tour/tuples.md
new file mode 100644
index 0000000000..27ba0d9819
--- /dev/null
+++ b/_es/tour/tuples.md
@@ -0,0 +1,91 @@
+---
+layout: tour
+title: Tuples
+partof: scala-tour
+num:
+language: es
+
+next-page: mixin-class-composition
+previous-page: inner-classes
+
+---
+
+En Scala, una tupla es un valor que contiene un número fijo de elementos,
+cada uno de ellos puede ser de distinto tipo. Las tuplas son inmutables.
+
+Las tuplas son especialmente útiles para retornar múltiples valores desde
+un método.
+
+Una tupla con dos elementos puede ser creada del siguiente modo:
+
+```scala mdoc
+val ingredient = ("Sugar", 25)
+```
+
+Esta instrucción crea una tupla que contiene un elemento de tipo `String`
+y un elemento de tipo `Int`.
+
+El tipo de la tupla `ingredient` se infiere que es`(String, Int)`, lo cual es
+una abreviatura de `Tuple2[String, Int]`.
+
+Para representar tuplas, Scala utiliza una serie de clases: `Tuple2`, `Tuple3`,
+etc., hasta `Tuple22`.
+Cada clase tiene tantos parámetros como número de elementos.
+
+## Accediendo a los elementos
+
+Una forma de acceder a los elementos de una tupla es por posición.
+Los elementos concretos se llaman `_1`, `_2`, y así sucesivamente.
+
+```scala mdoc
+println(ingredient._1) // Sugar
+println(ingredient._2) // 25
+```
+
+## Reconocimiento de patrones en tuplas
+
+Una tupla también puede ser dividida/expandida usando reconocimiento de patrones (pattern matching):
+
+```scala mdoc
+val (name, quantity) = ingredient
+println(name) // Sugar
+println(quantity) // 25
+```
+
+En esta ocasión el tipo de `name` es inferido como `String` y el de
+`quantity` como `Int`.
+
+A continuación otro ejemplo de reconocimiento de patrones con tuplas:
+
+```scala mdoc
+val planets =
+ List(("Mercury", 57.9), ("Venus", 108.2), ("Earth", 149.6),
+ ("Mars", 227.9), ("Jupiter", 778.3))
+planets.foreach{
+ case ("Earth", distance) =>
+ println(s"Nuestro planeta está a $distance millones de kilómetros del Sol.")
+ case _ =>
+}
+```
+
+O en compresión de bucles `for`:
+
+```scala mdoc
+val numPairs = List((2, 5), (3, -7), (20, 56))
+for ((a, b) <- numPairs) {
+ println(a * b)
+}
+```
+
+## Tuplas y case classes
+
+A veces los usuarios encuentran difícil elegir entre tuplas y clases Case.
+Los elementos de las clases Case tienen nombre. Los nombres pueden mejorar
+la lectura en el código.
+En el ejemplo anterior de los planetas, podríamos haber definido
+`case class Planet(name: String, distance: Double)` en vez de usar tuplas.
+
+
+## Más recursos
+
+* Aprende más acerca de las tuplas en el [Scala Book](/overviews/scala-book/tuples.html)
diff --git a/_es/tour/type-inference.md b/_es/tour/type-inference.md
index 0bbf7400fa..67e0b52099 100644
--- a/_es/tour/type-inference.md
+++ b/_es/tour/type-inference.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Inferencia de tipos Local
-
-discourse: false
-
partof: scala-tour
num: 29
@@ -33,7 +30,7 @@ Tampoco es obligatorio especificar el tipo de los parámetros cuando se trate de
Aquí se muestra un ejemplo que ilustra esto:
- case class MyPair[A, B](x: A, y: B);
+ case class MyPair[A, B](x: A, y: B)
object InferenceTest3 extends App {
def id[T](x: T) = x
val p = MyPair(1, "scala") // tipo: MyPair[Int, String]
diff --git a/_es/tour/unified-types.md b/_es/tour/unified-types.md
index d2f8bc76c2..3a1db1e651 100644
--- a/_es/tour/unified-types.md
+++ b/_es/tour/unified-types.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Tipos Unificados
-
-discourse: false
-
partof: scala-tour
num: 30
@@ -20,7 +17,7 @@ A diferencia de Java, todos los valores en Scala son objetos (incluyendo valores
## Jerarquía de clases en Scala ##
La superclase de todas las clases, `scala.Any`, tiene dos subclases directas, `scala.AnyVal` y `scala.AnyRef` que representan dos mundos de clases muy distintos: clases para valores y clases para referencias. Todas las clases para valores están predefinidas; se corresponden con los tipos primitivos de los lenguajes tipo Java. Todas las otras clases definen tipos referenciables. Las clases definidas por el usuario son definidas como tipos referenciables por defecto, es decir, siempre (indirectamente) extienden de `scala.AnyRef`. Toda clase definida por usuario en Scala extiende implicitamente el trait `scala.ScalaObject`. Clases pertenecientes a la infraestructura en la cual Scala esté corriendo (ejemplo, el ambiente de ejecución de Java) no extienden de `scala.ScalaObject`. Si Scala es usado en el contexto de un ambiente de ejecución de Java, entonces `scala.AnyRef` corresponde a `java.lang.Object`.
-Por favor note que el diagrama superior también muestra conversiones implícitas llamadas viestas entre las clases para valores.
+Por favor note que el diagrama superior también muestra conversiones implícitas llamadas vistas entre las clases para valores.
Aquí se muestra un ejemplo que demuestra que tanto valores numéricos, de caracteres, buleanos y funciones son objetos, tal como cualquier otro objeto:
diff --git a/_es/tour/upper-type-bounds.md b/_es/tour/upper-type-bounds.md
index 84124c8944..663915f957 100644
--- a/_es/tour/upper-type-bounds.md
+++ b/_es/tour/upper-type-bounds.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Límite de tipado superior
-
-discourse: false
-
partof: scala-tour
num: 25
@@ -13,7 +10,7 @@ next-page: lower-type-bounds
previous-page: traits
---
-En Scala, los [parámetros de tipo](generic-classes.html) y los [tipos abstractos](abstract-types.html) pueden ser restringidos por un límite de tipado. Tales límites de tipado limitan los valores concretos de las variables de tipo y posiblemente revelan más información acerca de los miembros de tales tipos. Un _límite de tipado superior_ `T <: A` declara que la variable de tipo `T` es un subtipo del tipo `A`.
+En Scala, los [parámetros de tipo](generic-classes.html) y los [tipos abstractos](abstract-type-members.html) pueden ser restringidos por un límite de tipado. Tales límites de tipado limitan los valores concretos de las variables de tipo y posiblemente revelan más información acerca de los miembros de tales tipos. Un _límite de tipado superior_ `T <: A` declara que la variable de tipo `T` es un subtipo del tipo `A`.
Aquí se muestra un ejemplo el cual se basa en un límite de tipado superior para la implementación del método polimórfico `findSimilar`:
trait Similar {
diff --git a/_es/tour/variances.md b/_es/tour/variances.md
index e437375545..eb961061a8 100644
--- a/_es/tour/variances.md
+++ b/_es/tour/variances.md
@@ -1,9 +1,6 @@
---
layout: tour
title: Varianzas
-
-discourse: false
-
partof: scala-tour
num: 31
@@ -17,7 +14,7 @@ Scala soporta anotaciones de varianza para parámetros de tipo para [clases gen
En el artículo sobre clases genéricas dimos un ejemplo de una pila mutable. Explicamos que el tipo definido por la clase `Stack[T]` es objeto de subtipos invariantes con respecto al parámetro de tipo. Esto puede restringir el reuso de la abstracción (la clase). Ahora derivaremos una implementación funcional (es decir, inmutable) para pilas que no tienen esta restricción. Nótese que este es un ejemplo avanzado que combina el uso de [métodos polimórficos](polymorphic-methods.html), [límites de tipado inferiores](lower-type-bounds.html), y anotaciones de parámetros de tipo covariante de una forma no trivial. Además hacemos uso de [clases internas](inner-classes.html) para encadenar los elementos de la pila sin enlaces explícitos.
-```tut
+```scala mdoc
class Stack[+T] {
def push[S >: T](elem: S): Stack[S] = new Stack[S] {
override def top: S = elem
diff --git a/_es/tutorials/scala-for-java-programmers.md b/_es/tutorials/scala-for-java-programmers.md
index 71a7ba6023..120d93d316 100644
--- a/_es/tutorials/scala-for-java-programmers.md
+++ b/_es/tutorials/scala-for-java-programmers.md
@@ -3,8 +3,6 @@ layout: singlepage-overview
title: Tutorial de Scala para programadores Java
partof: scala-for-java-programmers
-
-discourse: true
language: es
---
@@ -13,14 +11,14 @@ Traducción y arreglos Santiago Basulto.
## Introducción
-Este documento provee una rápida introducción al lenguaje Scala como también a su compilador. Está pensado para personas que ya poseen cierta experiencia en programación y quieren una vista rápida de lo que pueden hacer con Scala. Se asume como un conocimiento básico de programación orientada a objetos, especialmente en Java.
+Este documento provee una rápida introducción al lenguaje Scala como también a su compilador. Está pensado para personas que ya poseen cierta experiencia en programación y quieren una vista rápida de lo que pueden hacer con Scala. Se asume un conocimiento básico de programación orientada a objetos, especialmente en Java.
## Un primer ejemplo
Como primer ejemplo, usaremos el programa *Hola mundo* estándar. No es muy fascinante, pero de esta manera resulta fácil demostrar el uso de herramientas de Scala sin saber demasiado acerca del lenguaje. Veamos como luce:
object HolaMundo {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
println("¡Hola, mundo!")
}
}
@@ -35,7 +33,7 @@ El lector astuto notará que el método `main` no es declarado como `static`. Es
Para compilar el ejemplo utilizaremos `scalac`, el compilador de Scala. `scalac` funciona como la mayoría de los compiladores. Toma un archivo fuente como argumento, algunas opciones y produce uno o varios archivos objeto. Los archivos objeto que produce son archivos class de Java estándar.
-Si guardamos el programa anterior en un archivo llamado `HolaMundo.scala`, podemos compilarlo ejecutando el siguiente comando (el símbolo mayor `>` representa el prompt del shell y no debe ser escrita):
+Si guardamos el programa anterior en un archivo llamado `HolaMundo.scala`, podemos compilarlo ejecutando el siguiente comando (el símbolo mayor `>` representa el prompt del shell y no debe ser escrito):
> scalac HolaMundo.scala
@@ -58,11 +56,10 @@ Veamos un ejemplo que demuestra esto. Queremos obtener y formatear la fecha actu
Las librerías de clases de Java definen clases de utilería poderosas, como `Date` y `DateFormat`. Ya que Scala interacciona fácilmente con Java, no es necesario implementar estas clases equivalentes en las librerías de Scala --podemos simplemente importar las clases de los correspondientes paquetes de Java:
import java.util.{Date, Locale}
- import java.text.DateFormat
import java.text.DateFormat._
object FrenchDate {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val ahora = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format ahora)
@@ -71,7 +68,7 @@ Las librerías de clases de Java definen clases de utilería poderosas, como `Da
Las declaraciones de importación de Scala lucen muy similares a las de Java, sin embargo, las primeras son bastante más poderosas. Múltiples clases pueden ser importadas desde el mismo paquete al encerrarlas en llaves como se muestra en la primer línea. Otra diferencia es que podemos importar todos los nombres de un paquete o clase, utilizando el carácter guión bajo (`_`) en vez del asterisco (`*`). Eso es porque el asterisco es un identificador válido en Scala (quiere decir que por ejemplo podemos nombrar a un método `*`), como veremos más adelante.
-La declaración `import` en la tercer línea por lo tanto importa todos los miembros de la clase `DateFormat`. Esto hace que el método estático `getDateInstance` y el campo estático `LONG` sean directamente visibles.
+La declaración `import` en la segunda línea importa todos los miembros de la clase `DateFormat`. Esto hace que el método estático `getDateInstance` y el campo estático `LONG` sean directamente visibles.
Dentro del método `main` primero creamos una instancia de la clase `Date` la cual por defecto contiene la fecha actual. A continuación definimos un formateador de fechas utilizando el método estático `getDateInstance` que importamos previamente. Finalmente, imprimimos la fecha actual formateada de acuerdo a la instancia de `DateFormat` que fue "localizada". Esta última línea muestra una propiedad interesante de la sintaxis de Scala. Los métodos que toman un solo argumento pueden ser usados con una sintaxis de infijo Es decir, la expresión
@@ -97,23 +94,13 @@ Ya que los números son objetos, estos también tienen métodos. De hecho, una e
Consiste exclusivamente de llamadas a métodos, porque es equivalente a la siguiente expresión, como vimos en la sección anterior:
- (1).+(((2).*(3))./(x))
+ 1.+(2.*(3)./(x))
Esto también indica que `+`, `*`, etc. son identificadores válidos en Scala.
-Los paréntesis alrededor de los números en la segunda versión son necesarios porque el analizador léxico de Scala usa la regla de "mayor coincidencia". Por lo tanto partiría la siguiente expresión:
-
- 1.+(2)
-
-En estas partes: `1.`, `+`, y `2`. La razón que esta regla es elegida es porque `1.` es una coincidencia válida y es mayor que `1`, haciendo a este un `Double` en vez de un `Int`. Al escribir la expresión así:
-
- (1).+(2)
-
-previene que el `1` sea tomado como un `Double`.
-
### Las funciones son objetos
-Tal vez suene más sorprendente para los programadores Java, las funciones en Scala también son objetos. Por lo tanto es posible pasar funciones como argumentos, almacenarlas en variables, y retornarlas desde otras funciones. Esta habilidad de manipular funciones como valores es una de las valores fundamentales de un paradigma de programación muy interesante llamado *programación funcional*.
+Tal vez suene más sorprendente para los programadores Java, las funciones en Scala también son objetos. Por lo tanto es posible pasar funciones como argumentos, almacenarlas en variables, y retornarlas desde otras funciones. Esta habilidad de manipular funciones como valores es una de los valores fundamentales de un paradigma de programación muy interesante llamado *programación funcional*.
Como un ejemplo muy simple de por qué puede ser útil usar funciones como valores consideremos una función *temporizador* (o timer, en inglés) cuyo propósito es realizar alguna acción cada un segundo. ¿Cómo pasamos al temporizador la acción a realizar? Bastante lógico, como una función. Este simple concepto de pasar funciones debería ser familiar para muchos programadores: es generalmente utilizado en código relacionado con Interfaces gráficas de usuario (GUIs) para registrar "retrollamadas" (call-back en inglés) que son invocadas cuando un evento ocurre.
@@ -121,19 +108,20 @@ En el siguiente programa, la función del temporizador se llama `unaVezPorSegund
object Temporizador {
def unaVezPorSegundo(callback: () => Unit) {
- while (true) { callback(); Thread sleep 1000 }
+ while (true) {
+ callback();
+ Thread sleep 1000
+ }
}
def tiempoVuela() {
println("El tiempo vuela como una flecha...")
}
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
unaVezPorSegundo(tiempoVuela)
}
}
_Nota: si nunca tuviste experiencias previas con programación funcional te recomiendo que te tomes unos segundos para analizar cuando se utilizan paréntesis y cuando no en los lugares donde aparece *callback*. Por ejemplo, dentro de la declaración de `unaVezPorSegundo` no aparece, ya que se trata de la función como un "valor", a diferencia de cómo aparece dentro del método, ya que en ese caso se la está invocando (por eso los paréntesis)._
-Note that in order to print the string, we used the predefined method
-`println` instead of using the one from `System.out`.
#### Funciones anónimas
@@ -141,9 +129,12 @@ El programa anterior es fácil de entender, pero puede ser refinado aún más. P
object TemporizadorAnonimo {
def unaVezPorSegundo(callback: () => Unit) {
- while (true) { callback(); Thread sleep 1000 }
+ while (true) {
+ callback();
+ Thread sleep 1000
+ }
}
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
unaVezPorSegundo(
() => println("El tiempo vuela como una flecha...")
)
@@ -176,7 +167,7 @@ El compilador no es siempre capaz de inferir los tipos como lo hace aquí, y des
Un pequeño problema de los métodos `re` e `im` es que para poder llamarlos es necesario agregar un par de paréntesis vacíos después de sus nombres, como muestra el siguiente ejemplo:
object NumerosComplejos {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val c = new Complejo(1.2, 3.4)
println("Parte imaginaria: " + c.im())
}
@@ -253,15 +244,15 @@ De ahora en más, el tipo `Entorno` puede ser usado como un alias del tipo de fu
Ahora podemos dar la definición de la función evaluadora. Conceptualmente, es muy sencillo: el valor de una suma de dos expresiones es simplemente la suma de los valores de estas expresiones; el valor de una variable es obtenido directamente del entorno; y el valor de una constante es la constante en sí misma. Expresar esto en Scala no resulta para nada difícil:
def eval(a: Arbol, ent: Entorno): Int = a match {
- case Sum(i, d) => eval(i, ent) + eval(d, env)
+ case Sum(i, d) => eval(i, ent) + eval(d, ent)
case Var(n) => ent(n)
case Const(v) => v
}
Esta función evaluadora función realizando un *reconocimiento de patrones* (pattern matching) en el árbol `a`. Intuitivamente, el significado de la definición de arriba debería estar claro:
-1. Primero comprueba si el árbol `t`es una `Sum`, y si lo es, asocia el sub-arbol izquierdo a una nueva variable llamada `i` y el sub-arbol derecho a la variable `r`, y después procede con la evaluación de la expresión que sigue a la flecha (`=>`); esta expresión puede (y hace) uso de las variables asociadas por el patrón que aparece del lado izquierdo de la flecha.
-2. si la primer comprobación (la de `Sum`) no prospera, es decir que el árbol no es una `Sum`, sigue de largo y comprueba si `a` es un `Var`; si lo es, asocia el nombre contenido en el nodo `Var` a la variable `n` y procede con la parte derecha de la expresión.
+1. Primero comprueba si el árbol `t`es una `Sum`, y si lo es, asocia el sub-arbol izquierdo a una nueva variable llamada `i` y el sub-arbol derecho a la variable `d`, y después procede con la evaluación de la expresión que sigue a la flecha (`=>`); esta expresión puede (y hace) uso de las variables asociadas por el patrón que aparece del lado izquierdo de la flecha.
+2. Si la primer comprobación (la de `Sum`) no prospera, es decir que el árbol no es una `Sum`, sigue de largo y comprueba si `a` es un `Var`; si lo es, asocia el nombre contenido en el nodo `Var` a la variable `n` y procede con la parte derecha de la expresión.
3. si la segunda comprobación también falla, resulta que `a` no es un `Sum` ni un `Var`, por lo tanto comprueba que sea un `Const`, y si lo es, asocia el valor contenido en el nodo `Const` a la variable `v`y procede con el lado derecho.
4. finalmente, si todos las comprobaciones fallan, una excepción es lanzada para dar cuenta el fallo de la expresión; esto puede pasar solo si existen más subclases de `Arbol`.
@@ -279,7 +270,7 @@ Para explorar un poco más esto de pattern matching definamos otra operación ar
2. la derivada de una variable `v` es uno (1) si `v` es la variable relativa a la cual la derivada toma lugar, y cero (0)de otra manera,
3. la derivada de una constante es cero (0).
-Estas reglas pueden ser traducidas casi literalmente en código Sclaa, para obtener la siguiente definición.
+Estas reglas pueden ser traducidas casi literalmente en código Scala, para obtener la siguiente definición.
def derivada(a: Arbol, v: String): Arbol = a match {
case Sum(l, r) => Sum(derivada(l, v), derivada(r, v))
@@ -291,7 +282,7 @@ Esta función introduce dos nuevos conceptos relacionados al pattern matching. P
No hemos explorado el completo poder del pattern matching aún, pero nos detendremos aquí para mantener este documento corto. Todavía nos queda pendiente ver cómo funcionan las dos funciones de arriba en un ejemplo real. Para ese propósito, escribamos una función main simple que realice algunas operaciones sobre la expresión `(x+x)+(7+y)`: primero computa su valor en el entorno `{ x -> 5, y -> 7 }` y después computa su derivada con respecto a `x` y después a `y`.
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val exp: Arbol = Sum(Sum(Var("x"),Var("x")),Sum(Const(7),Var("y")))
val ent: Entonrno = { case "x" => 5 case "y" => 7 }
println("Expresión: " + exp)
@@ -321,7 +312,7 @@ Tal vez la forma más fácil para un programador Java de entender qué son los t
Para ver la utilidad de los traits, veamos un ejemplo clásico: objetos ordenados. Generalmente es útil tener la posibilidad de comparar objetos de una clase dada entre ellos, por ejemplo, para ordenarlos. En Java, los objetos que son comparables implementan la interfaz `Comparable`. En Scala, podemos hacer algo un poco mejor que en Java al definir un trait equivalente `Comparable` que invocará a `Ord`.
-Cuando comparamos objetos podemos utilizar seis predicados distintos: menor, menor o igual, igual, distinto, mayor o igual y mayor. De todas maneras, definir todos estos es fastidioso, especialmente que cuatro de estos pueden ser expresados en base a los otros dos. Esto es, dados los predicados "igual" y "menor" (por ejemplo), uno puede expresar los otros. En Scala, todas estas observaciones pueden ser fácilmente capturadas mediante la siguiente declaración de un Trait:
+Cuando comparamos objetos podemos utilizar seis predicados distintos: menor, menor o igual, igual, distinto, mayor o igual y mayor. De todas maneras, definir todos estos es fastidioso, especialmente cuando cuatro de éstos pueden ser expresados en base a los otros dos. Esto es, dados los predicados "igual" y "menor" (por ejemplo), uno puede expresar los otros. En Scala, todas estas observaciones pueden ser fácilmente capturadas mediante la siguiente declaración de un Trait:
trait Ord {
def < (that: Any): Boolean
@@ -358,7 +349,7 @@ Finalmente el último método para definir es el predicado que comprueba la infe
def <(that: Any): Boolean = {
if (!that.isInstanceOf[Fecha])
- error("no se puede comparar" + that + " y una fecha")
+ sys.error("no se puede comparar" + that + " y una fecha")
val o = that.asInstanceOf[Fecha]
(anno < o.anno) ||
@@ -395,10 +386,10 @@ El ejemplo anterior introduce a las variables en Scala, que no deberían requeri
Para utilizar esta clase `Referencia`, uno necesita especificar qué tipo utilizar por el parámetro `T`, es decir, el tipo del elemento contenido por la referencia. Por ejemplo, para crear y utilizar una referencia que contenga un entero, podríamos escribir lo siguiente:
object ReferenciaEntero {
- def main(args: Array[String]) {
+ def main(args: Array[String]): Unit = {
val ref = new Referencia[Int]
ref.set(13)
- println("La referncia tiene la mitad de " + (ref.get * 2))
+ println("La referencia tiene la mitad de " + (ref.get * 2))
}
}
diff --git a/_fr/cheatsheets/index.md b/_fr/cheatsheets/index.md
index 9cb47c6f8d..953bfca164 100644
--- a/_fr/cheatsheets/index.md
+++ b/_fr/cheatsheets/index.md
@@ -1,11 +1,11 @@
---
layout: cheatsheet
-title: Scalacheat
+title: Scala Cheatsheet
partof: cheatsheet
by: Brendan O'Connor
-about: Grâce à Brendan O'Connor, ce memento vise à être un guide de référence rapide pour les constructions syntaxiques en Scala. Licencié par Brendan O'Connor sous licence CC-BY-SA 3.0.
+about: Grâce à Brendan O'Connor, ce memento vise à être un guide de référence rapide pour les constructions syntaxiques en Scala. Licencié par Brendan O'Connor sous licence CC-BY-SA 3.0.
language: fr
---
@@ -47,7 +47,7 @@ language: fr
| `var (x,y,z) = (1,2,3)` | liaison déstructurée : le déballage du tuple se fait par le "pattern matching". |
| Bad`var x,y,z = (1,2,3)` | erreur cachée : chaque variable est associée au tuple au complet. |
| `var xs = List(1,2,3)` | liste (immuable). |
-| `xs(2)` | indexe un élément par le biais des parenthèses. ([transparents](http://www.slideshare.net/Odersky/fosdem-2009-1013261/27)) |
+| `xs(2)` | indexe un élément par le biais des parenthèses. ([transparents](https://www.slideshare.net/Odersky/fosdem-2009-1013261/27)) |
| `1 :: List(2,3)` | créé une liste par le biais de l'opérateur "cons".|
| `1 to 5` _est équivalent à_ `1 until 6` `1 to 10 by 2` | sucre syntaxique pour les plages de valeurs. |
| `()` _(parenthèses vides)_ | l'unique membre de type Unit (à l'instar de void en C/Java). |
@@ -56,11 +56,11 @@ language: fr
| `if (check) happy` _est équivalent à_ `if (check) happy else ()` | sucre syntaxique pour un test conditionnel. |
| `while (x < 5) { println(x); x += 1}` | boucle while. |
| `do { println(x); x += 1} while (x < 5)` | boucle do while. |
-| `import scala.util.control.Breaks._` `breakable {` ` for (x <- xs) {` ` if (Math.random < 0.1) break` ` }` `}`| break. ([transparents](http://www.slideshare.net/Odersky/fosdem-2009-1013261/21)) |
+| `import scala.util.control.Breaks._` `breakable {` ` for (x <- xs) {` ` if (Math.random < 0.1) break` ` }` `}`| break. ([transparents](https://www.slideshare.net/Odersky/fosdem-2009-1013261/21)) |
| `for (x <- xs if x%2 == 0) yield x*10` _est équivalent à_ `xs.filter(_%2 == 0).map(_*10)` | *for comprehension*: filter/map |
| `for ((x,y) <- xs zip ys) yield x*y` _est équivalent à_ `(xs zip ys) map { case (x,y) => x*y }` | *for comprehension* : liaison déstructurée |
| `for (x <- xs; y <- ys) yield x*y` _est équivalent à_ `xs flatMap {x => ys map {y => x*y}}` | *for comprehension* : produit cartésien. |
-| `for (x <- xs; y <- ys) {` `println("%d/%d = %.1f".format(x, y, x/y.toFloat))` `}` | *for comprehension* : à la manière impérative [sprintf-style](http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax) |
+| `for (x <- xs; y <- ys) {` `println("%d/%d = %.1f".format(x, y, x/y.toFloat))` `}` | *for comprehension* : à la manière impérative [sprintf-style](https://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax) |
| `for (i <- 1 to 5) {` `println(i)` `}` | *for comprehension* : itère jusqu'à la borne supérieure comprise. |
| `for (i <- 1 until 5) {` `println(i)` `}` | *for comprehension* : itère jusqu'à la borne supérieure non comprise. |
| pattern matching | |
diff --git a/_fr/getting-started/install-scala.md b/_fr/getting-started/install-scala.md
new file mode 100644
index 0000000000..76f7c537f9
--- /dev/null
+++ b/_fr/getting-started/install-scala.md
@@ -0,0 +1,198 @@
+---
+layout: singlepage-overview
+title: Démarrage
+partof: getting-started
+language: fr
+includeTOC: true
+---
+
+Les instructions ci-dessous couvrent à la fois Scala 2 et Scala 3.
+
+## Essayer Scala sans installation
+
+Pour commencer à expérimenter Scala sans plus attendre, utilisez “Scastie” dans votre navigateur _Scastie_ est un environnement "bac à sable" en ligne, où vous pouvez tester Scala, afin de comprendre comment fonctionne le langage et avec un accès à tous les compilateurs Scala et les librairies publiées.
+
+> Scastie supporte à la fois Scala 2 et Scala 3, en proposant Scala 3 par défaut.
+> Si vous cherchez à tester un morceau de code avec Scala 2
+> [cliquez ici](https://scastie.scala-lang.org/MHc7C9iiTbGfeSAvg8CKAA).
+
+## Installer Scala sur votre ordinateur
+
+Installer Scala veut dire installer différents outils en ligne de commande, comme le compilateur Scala et les outils de build.
+Nous recommandons l'utilisation de l'outil d'installation "Coursier" qui va automatiquement installer toutes les dépendances, mais vous pouvez aussi installer chaque outil à la main.
+
+### Utilisation de l'installateur Scala (recommandé)
+
+L'installateur Scala est un outil nommé [Coursier](https://get-coursier.io/docs/cli-overview), la commande principale de l'outil est `cs`.
+Il s'assure que la JVM est les outils standards de Scala sont installés sur votre système.
+Installez-le sur votre système avec les instructions suivantes.
+
+
+{% tabs install-cs-setup-tabs class=platform-os-options %}
+
+
+{% tab macOS for=install-cs-setup-tabs %}
+{% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.macOS-brew %}
+{% altDetails cs-setup-macos-nobrew "Alternativement, si vous n'utilisez pas Homebrew:" %}
+ {% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.macOS-x86-64 %}
+{% endaltDetails %}
+{% endtab %}
+
+
+
+{% tab Linux for=install-cs-setup-tabs %}
+ {% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.linux-x86-64 %}
+{% endtab %}
+
+
+
+{% tab Windows for=install-cs-setup-tabs %}
+ Téléchargez et exécutez [l'intallateur Scala pour Windows]({{site.data.setup-scala.windows-link}}) basé sur Coursier.
+{% endtab %}
+
+
+
+{% tab Other for=install-cs-setup-tabs defaultTab %}
+
+ Suivez
+ [les instructions pour installer la commande `cs`](https://get-coursier.io/docs/cli-installation)
+ puis exécutez `./cs setup`.
+{% endtab %}
+
+
+{% endtabs %}
+
+
+En plus de gérer les JVMs, `cs setup` installe aussi des utilitaires en ligne de commande :
+
+- Un JDK (si vous n'en avez pas déjà un)
+- L'outil de construction de package [sbt](https://www.scala-sbt.org/)
+- [Ammonite](https://ammonite.io/), un REPL amélioré
+- [scalafmt](https://scalameta.org/scalafmt/), le formatteur de code Scala
+- `scalac` (le compilateur Scala 2)
+- `scala` (le REPL et le lanceur de script Scala 2).
+
+Pour plus d'informations à propos de `cs`, vous pouvez lire la page suivante :
+[coursier-cli documentation](https://get-coursier.io/docs/cli-overview).
+
+> Actuellement, `cs setup` installe le compilateur Scala 2 et le lanceur
+> (les commandes `scalac` et `scala` respectivement). Ce n'est pas un problème,
+> car la plupart des projets utilisent un outil de contruction
+> de package qui fonctionne à la fois pour Scala 2 et Scala 3.
+> Cependant, vous pouvez installer le compilateur et le lanceur Scala 3 en ligne de commande,
+> en exécutant les commandes suivantes :
+> ```
+> $ cs install scala3-compiler
+> $ cs install scala3
+> ```
+
+### ...ou manuellement
+
+Vous avez seulement besoin de deux outils pour compiler, lancer, tester et packager un projet Scala: Java 8 ou 11, et sbt.
+Pour les installer manuellement :
+
+1. Si vous n'avez pas Java 8 ou 11 installé, téléchargez
+ Java depuis [Oracle Java 8](https://www.oracle.com/java/technologies/javase-jdk8-downloads.html), [Oracle Java 11](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html),
+ ou [AdoptOpenJDK 8/11](https://adoptopenjdk.net/). Référez-vous à la page [JDK Compatibility](/overviews/jdk-compatibility/overview.html) pour les détails de compatibilité entre Java et Scala.
+1. Installez [sbt](https://www.scala-sbt.org/download.html)
+
+## Créer un projet "Hello World" avec sbt
+
+Une fois que vous avez installé sbt, vous pouvez créer un projet Scala, comme expliqué dans la section suivante.
+
+Pour créer un projet, vous pouvez soit utiliser la ligne de commande, soit un IDE.
+Si vous êtes habitué à la ligne de commande, nous recommandons cette approche.
+
+### Utiliser la ligne de commande
+
+sbt est un outil de construction de package pour Scala, sbt compile, lance et teste votre code Scala.
+(Il peut aussi publier les librairies et faire beaucoup d'autres tâches.)
+
+Pour créer un nouveau projet Scala avec sbt :
+
+1. `cd` dans un répertoire vide.
+1. Lancez la commande `sbt new scala/scala3.g8` pour créer un projet Scala 3, ou `sbt new scala/hello-world.g8` pour créer un projet Scala 2.
+ Cela va télécharger un projet modèle depuis Github.
+ Cela va aussi créer un dossier `target`, que vous pouvez ignorer.
+1. Quand cela vous est demandé, nommez votre application `hello-world`. Cela va créer un projet appelé "hello-world".
+1. Voyons ce que nous vennons de générer :
+
+```
+- hello-world
+ - project (sbt utilise ce dossier pour ses propres fichiers)
+ - build.properties
+ - build.sbt (fichier de définition de la construction du package pour sbt)
+ - src
+ - main
+ - scala (tout votre code Scala doit être placé ici)
+ - Main.scala (Point d'entrée du programme) <-- c'est tout ce dont nous avons besoin pour le moment
+```
+
+Vous pouvez trouver plus de documentation à propos de sbt dans le [Scala Book](/scala3/book/tools-sbt.html) ([Lien](/overviews/scala-book/scala-build-tool-sbt.html) vers la version Scala 2) et sur la [documentation](https://www.scala-sbt.org/1.x/docs/index.html) officielle de sbt.
+
+### Avec un IDE
+
+Vous pouvez ignorer le reste de cette page et aller directement sur [Building a Scala Project with IntelliJ and sbt](/getting-started/intellij-track/building-a-scala-project-with-intellij-and-sbt.html).
+
+
+## Ouvrir le projet hello-world
+
+Utilisons un IDE pour ouvrir le projet. Les plus populaires sont IntelliJ et VSCode.
+Il proposent tout deux des fonctionnalités avancées. D'[autres éditeurs](https://scalameta.org/metals/docs/editors/overview.html) sont également disponibles.
+
+### Avec IntelliJ
+
+1. Téléchargez et installez [IntelliJ Community Edition](https://www.jetbrains.com/idea/download/)
+1. Installez l'extension Scala en suivant [les instruction IntelliJ pour installer des extensions](https://www.jetbrains.com/help/idea/managing-plugins.html)
+1. Ouvrez le fichier `build.sbt` puis choisissez *Open as a project*
+
+### Avec VSCode et metals
+
+1. Téléchargez [VSCode](https://code.visualstudio.com/Download)
+1. Installez l'extension Metals depuis [la marketplace](https://marketplace.visualstudio.com/items?itemName=scalameta.metals)
+1. Ensuite, ouvrez le répertoire contenant le fichier `build.sbt` (cela doit être le dossier `hello-world` si vous avez suivi les instructions précédentes). Choisissez *Import build* lorsque cela vous est demandé.
+
+> [Metals](https://scalameta.org/metals) est un "Serveur de langage Scala" qui fournit une aide pour écrire du code Scala dans VSCode et d'autres éditeurs [Atom, Sublime Text, autres ...](https://scalameta.org/metals/docs/editors/overview.html), en utilisant le [Language Server Protocol (LSP)](https://microsoft.github.io/language-server-protocol/).
+> En arrière plan, Metals communique avec l'outil de construction de package en utilisant
+> le [Build Server Protocol (BSP)](https://build-server-protocol.github.io/).
+> Pour plus de détails sur le fonctionnement de Metals, suivez [“Write Scala in VS Code, Vim, Emacs, Atom and Sublime Text with Metals”](https://www.scala-lang.org/2019/04/16/metals.html).
+
+### Essayer avec le code source
+
+Ouvrez ces deux fichiers dans votre IDE :
+
+- _build.sbt_
+- _src/main/scala/Main.scala_
+
+Quand vous lancerez votre projet à l'étape suivante, la configuration dans _build.sbt_ sera utilisée pour lancer le code dans _src/main/scala/Main.scala_.
+
+## Lancer Hello Word
+
+Si vous êtes habitué à votre IDE, vous pouvez lancer le code dans _Main.scala_ depuis celui-ci.
+
+Sinon, vous pouvez lancer l'application depuis le terminal avec ces étapes :
+
+1. `cd` vers `hello-world`.
+1. Lancez `sbt`. Cela va ouvrir la console sbt.
+1. Ecrivez `~run`. Le symbole `~` est optionnel, il va relancer l'application à chaque sauvegarde de fichier.
+ Cela permet un cyle rapide de modification/relance/debug. sbt va aussi générer un dossier `target` que vous pouvez ignorer.
+
+Quand vous avez fini d'expérimenter avec ce projet, appuyez sur `[Entrée]` pour interrompre la commande `run`.
+Puis saisissez `exit` ou appuyez sur `[Ctrl+D]` pour quitter sbt et revenir à votre invite de commande.
+
+## Prochaines étapes
+
+Une fois que vous avez terminé le tutoriel ce dessus, vous pouvez consulter :
+
+* [The Scala Book](/scala3/book/introduction.html) ([Lien](/overviews/scala-book/introduction.html) vers la version Scala 2), qui fournit un ensemble de courtes leçons et introduit les fonctionnalités principales de Scala.
+* [The Tour of Scala](/tour/tour-of-scala.html) pour une introduction des fonctionnalités Scala.
+* [Learning Courses](/online-courses.html), qui contient des tutoriels et des cours interactifs.
+* [Our list of some popular Scala books](/books.html).
+* [The migration guide](/scala3/guides/migration/compatibility-intro.html) pour vous aider à migrer votre code Scala 2 vers Scala 3.
+
+## Obtenir de l'aide
+Il y a plusieurs listes de diffusion et canaux de discussions instantanés si vous souhaitez rencontrer rapidement d'autres utilisateurs de Scala. Allez faire un tour sur notre page [community](https://scala-lang.org/community/) pour consulter la liste des ces ressources et obtenir de l'aide.
+
+Traduction par Antoine Pointeau.
diff --git a/_fr/tour/abstract-type-members.md b/_fr/tour/abstract-type-members.md
new file mode 100644
index 0000000000..68f1cdfd1e
--- /dev/null
+++ b/_fr/tour/abstract-type-members.md
@@ -0,0 +1,76 @@
+---
+layout: tour
+title: Abstract Type Members
+partof: scala-tour
+num: 25
+language: fr
+next-page: compound-types
+previous-page: inner-classes
+topics: abstract type members
+prerequisite-knowledge: variance, upper-type-bound
+---
+
+Les types abstraits, tels que les traits et les classes abstraites, peuvent avoir des membres type abstrait.
+Cela signifie que les implémentations concrètes définissent les types réels.
+Voici un exemple :
+
+```scala mdoc
+trait Buffer {
+ type T
+ val element: T
+}
+```
+
+Ici, nous avons défini un `type T` abstrait. Il est utilisé pour décrire le type de `element`. Nous pouvons étendre ce trait dans une classe abstraite, en ajoutant une borne de type supérieure à `T` pour le rendre plus spécifique.
+
+```scala mdoc
+abstract class SeqBuffer extends Buffer {
+ type U
+ type T <: Seq[U]
+ def length = element.length
+}
+```
+
+Remarquez comment nous pouvons utiliser un autre type abstrait `U` dans la spécification d'une borne supérieure pour `T`. Cette `class SeqBuffer` nous permet de stocker uniquement des séquences dans le tampon en indiquant que le type `T` doit être un sous-type de `Seq[U]` pour un nouveau type abstrait `U`.
+
+Les traits ou [classes](classes.html) avec des membres type abstrait sont souvent utilisés en combinaison avec des instanciations de classes anonymes. Pour illustrer cela, regardons maintenant un programme qui traite un "sequence buffer" qui fait référence à une liste d'entiers :
+
+```scala mdoc
+abstract class IntSeqBuffer extends SeqBuffer {
+ type U = Int
+}
+
+
+def newIntSeqBuf(elem1: Int, elem2: Int): IntSeqBuffer =
+ new IntSeqBuffer {
+ type T = List[U]
+ val element = List(elem1, elem2)
+ }
+val buf = newIntSeqBuf(7, 8)
+println("length = " + buf.length)
+println("content = " + buf.element)
+```
+
+Ici, la factory `newIntSeqBuf` utilise une implémentation de classe anonyme de `IntSeqBuffer` (c'est-à-dire `new IntSeqBuffer`) pour définir le type abstrait `T` comme étant le type concret `List[Int]`.
+
+Il est également possible de transformer des membres type abstrait en paramètres de type de classes et *vice versa*. Voici une version du code ci-dessous qui n'utilise que des paramètres de type :
+
+```scala mdoc:nest
+abstract class Buffer[+T] {
+ val element: T
+}
+abstract class SeqBuffer[U, +T <: Seq[U]] extends Buffer[T] {
+ def length = element.length
+}
+
+def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] =
+ new SeqBuffer[Int, List[Int]] {
+ val element = List(e1, e2)
+ }
+
+val buf = newIntSeqBuf(7, 8)
+println("length = " + buf.length)
+println("content = " + buf.element)
+```
+
+Notez que nous devons utiliser ici [les annotaions de variance](variances.html) (`+T <: Seq[U]`) afin de masquer le type concret d'implémentation de séquence dans l'objet renvoyé par la méthode `newIntSeqBuf`. De plus, il existe des cas où il n'est pas possible de remplacer les membres de type abstrait par des paramètres de type.
diff --git a/_fr/tour/annotations.md b/_fr/tour/annotations.md
new file mode 100644
index 0000000000..5f2b4cbf55
--- /dev/null
+++ b/_fr/tour/annotations.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Annotations
+partof: scala-tour
+
+num: 30
+
+language: fr
+
+next-page: packages-and-imports
+previous-page: by-name-parameters
+---
diff --git a/_fr/tour/basics.md b/_fr/tour/basics.md
new file mode 100644
index 0000000000..a16e3c7970
--- /dev/null
+++ b/_fr/tour/basics.md
@@ -0,0 +1,11 @@
+---
+layout: tour
+title: Basics
+partof: scala-tour
+
+num: 2
+language: fr
+
+next-page: unified-types
+previous-page: tour-of-scala
+---
diff --git a/_fr/tour/by-name-parameters.md b/_fr/tour/by-name-parameters.md
new file mode 100644
index 0000000000..917e78aede
--- /dev/null
+++ b/_fr/tour/by-name-parameters.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: By-name Parameters
+partof: scala-tour
+
+num: 29
+
+language: fr
+
+next-page: annotations
+previous-page: operators
+---
diff --git a/_fr/tour/case-classes.md b/_fr/tour/case-classes.md
new file mode 100644
index 0000000000..66debb53f4
--- /dev/null
+++ b/_fr/tour/case-classes.md
@@ -0,0 +1,73 @@
+---
+layout: tour
+title: Case Classes
+partof: scala-tour
+
+num: 13
+
+language: fr
+
+next-page: pattern-matching
+previous-page: multiple-parameter-lists
+---
+
+Les classes de cas sont comme les autres classes avec quelques différences que nous allons présenter. Les classes de cas sont pratiques pour modéliser des données immuables. Dans la prochaine étape du tour, nous verrons comment elles peuvent être utilisées avec le [pattern matching](pattern-matching.html).
+
+## Définir une classe de cas
+
+Une classe de cas requiert au minimum le mot clef `case class`, un identifiant, et une liste de paramètres (qui peut être vide) :
+
+```scala mdoc
+case class Book(isbn: String)
+
+val frankenstein = Book("978-0486282114")
+```
+
+Notez que le mot clef `new` n'a pas été utilisé pour instancier la classe de cas `Book`. C'est parce que la classe de cas a une méthode `apply` par défaut qui prend en charge la construction de l'objet.
+
+Quand vous créez une classe de cas avec des paramètres, les paramètres sont des `val` publiques.
+
+```
+case class Message(sender: String, recipient: String, body: String)
+val message1 = Message("guillaume@quebec.ca", "jorge@catalonia.es", "Ça va ?")
+
+println(message1.sender) // prints guillaume@quebec.ca
+message1.sender = "travis@washington.us" // cette ligne ne compile pas
+```
+
+Vous ne pouvez pas réaffecter `message1.sender` parce que c'est une `val` (càd. une valeur immuable). Il est possible d'utiliser des `var` dans les classes de cas mais ce n'est pas recommandé.
+
+## Comparaison
+
+Les instances des classes de cas sont comparées structurellement et non par référence :
+
+```scala mdoc
+case class Message(sender: String, recipient: String, body: String)
+
+val message2 = Message("jorge@catalonia.es", "guillaume@quebec.ca", "Com va?")
+val message3 = Message("jorge@catalonia.es", "guillaume@quebec.ca", "Com va?")
+val messagesAreTheSame = message2 == message3 // true
+```
+
+Même si `message2` et `message3` font référence à des objets différents, les valeurs de chaque objet sont égales.
+
+## Copier
+
+Vous pouvez créer une copie (superficielle) d'une instance de classe de cas simplement en utlisant la méthode `copy`. Vous pouvez optionnellement changer les arguments du constructeur.
+
+```scala mdoc:nest
+case class Message(sender: String, recipient: String, body: String)
+val message4 = Message("julien@bretagne.fr", "travis@washington.us", "Me zo o komz gant ma amezeg")
+val message5 = message4.copy(sender = message4.recipient, recipient = "claire@bourgogne.fr")
+message5.sender // travis@washington.us
+message5.recipient // claire@bourgogne.fr
+message5.body // "Me zo o komz gant ma amezeg"
+```
+
+Le destinataire (recipient) de `message4` est utilisé comment expéditeur (sender) du message `message5` mais le `body` du `message4` a été directement copié.
+
+## Plus d'informations
+
+* Apprennez-en plus sur les classes de cas dans [Scala Book](/overviews/scala-book/case-classes.html)
+
+Traduit par Antoine Pointeau.
diff --git a/_fr/tour/classes.md b/_fr/tour/classes.md
new file mode 100644
index 0000000000..40f56d0513
--- /dev/null
+++ b/_fr/tour/classes.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Classes
+partof: scala-tour
+
+num: 4
+
+language: fr
+
+next-page: traits
+previous-page: unified-types
+---
diff --git a/_fr/tour/compound-types.md b/_fr/tour/compound-types.md
new file mode 100644
index 0000000000..db813518b1
--- /dev/null
+++ b/_fr/tour/compound-types.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Compound Types
+partof: scala-tour
+
+num: 22
+
+language: fr
+
+next-page: self-types
+previous-page: abstract-type-members
+---
diff --git a/_fr/tour/default-parameter-values.md b/_fr/tour/default-parameter-values.md
new file mode 100644
index 0000000000..0f73ab1653
--- /dev/null
+++ b/_fr/tour/default-parameter-values.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Default Parameter Values
+partof: scala-tour
+
+num: 31
+
+language: fr
+
+next-page: named-arguments
+previous-page: annotations
+---
diff --git a/_fr/tour/extractor-objects.md b/_fr/tour/extractor-objects.md
new file mode 100644
index 0000000000..1f864b7f39
--- /dev/null
+++ b/_fr/tour/extractor-objects.md
@@ -0,0 +1,66 @@
+---
+layout: tour
+title: Extractor Objects
+partof: scala-tour
+
+num: 18
+
+language: fr
+
+next-page: for-comprehensions
+previous-page: regular-expression-patterns
+---
+
+Un objet extracteur est un objet avec une méthode `unapply`. Tandis que la méthode `apply` ressemble à un constructeur qui prend des arguments et crée un objet, `unapply` prend un object et essaye de retourner ses arguments. Il est utilisé le plus souvent en filtrage par motif (*pattern matching*) ou avec les fonctions partielles.
+
+```scala mdoc
+import scala.util.Random
+
+object CustomerID {
+
+ def apply(name: String) = s"$name--${Random.nextLong()}"
+
+ def unapply(customerID: String): Option[String] = {
+ val stringArray: Array[String] = customerID.split("--")
+ if (stringArray.tail.nonEmpty) Some(stringArray.head) else None
+ }
+}
+
+val customer1ID = CustomerID("Sukyoung") // Sukyoung--23098234908
+customer1ID match {
+ case CustomerID(name) => println(name) // prints Sukyoung
+ case _ => println("Could not extract a CustomerID")
+}
+```
+
+La méthode `apply` crée une chaîne de caractères `CustomerID` depuis `name`. La méthode `unapply` fait l'inverse pour retrouver le `name`. Lorsqu'on appelle `CustomerID("Sukyoung")`, c'est un raccourci pour `CustomerID.apply("Sukyoung")`. Lorsqu'on appelle `case CustomerID(name) => println(name)`, on appelle la méthode `unapply` avec `CustomerID.unapply(customer1ID)`.
+
+Sachant qu'une définition de valeur peut utiliser une décomposition pour introduire une nouvelle variable, un extracteur peut être utilisé pour initialiser la variable, avec la méthode `unapply` pour fournir la valeur.
+
+```scala mdoc
+val customer2ID = CustomerID("Nico")
+val CustomerID(name) = customer2ID
+println(name) // prints Nico
+```
+
+C'est équivalent à `val name = CustomerID.unapply(customer2ID).get`.
+
+```scala mdoc
+val CustomerID(name2) = "--asdfasdfasdf"
+```
+
+S'il n'y a pas de correspondance, une `scala.MatchError` est levée :
+
+```scala
+val CustomerID(name3) = "-asdfasdfasdf"
+```
+
+Le type de retour de `unapply` doit être choisi comme suit :
+
+* Si c'est juste un test, retourner un `Boolean`. Par exemple, `case even()`.
+* Si cela retourne une seule sous-valeur de type T, retourner un `Option[T]`.
+* Si vous souhaitez retourner plusieurs sous-valeurs `T1,...,Tn`, groupez-les dans un tuple optionnel `Option[(T1,...,Tn)]`.
+
+Parfois, le nombre de valeurs à extraire n'est pas fixe et on souhaiterait retourner un nombre arbitraire de valeurs, en fonction des données d'entrée. Pour ce cas, vous pouvez définir des extracteurs avec la méthode `unapplySeq` qui retourne un `Option[Seq[T]]`. Un exemple commun d'utilisation est la déconstruction d'une liste en utilisant `case List(x, y, z) =>`. Un autre est la décomposition d'une `String` en utilisant une expression régulière `Regex`, comme `case r(name, remainingFields @ _*) =>`.
+
+Traduit par Antoine Pointeau.
diff --git a/_fr/tour/for-comprehensions.md b/_fr/tour/for-comprehensions.md
new file mode 100644
index 0000000000..ea4649ad39
--- /dev/null
+++ b/_fr/tour/for-comprehensions.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: For Comprehensions
+partof: scala-tour
+
+num: 15
+
+language: fr
+
+next-page: generic-classes
+previous-page: extractor-objects
+---
diff --git a/_fr/tour/generic-classes.md b/_fr/tour/generic-classes.md
new file mode 100644
index 0000000000..6eeb2e8fea
--- /dev/null
+++ b/_fr/tour/generic-classes.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Generic Classes
+partof: scala-tour
+
+num: 16
+
+language: fr
+
+next-page: variances
+previous-page: extractor-objects
+---
diff --git a/_fr/tour/higher-order-functions.md b/_fr/tour/higher-order-functions.md
new file mode 100644
index 0000000000..513f6b619f
--- /dev/null
+++ b/_fr/tour/higher-order-functions.md
@@ -0,0 +1,123 @@
+---
+layout: tour
+title: Higher-order Functions
+partof: scala-tour
+
+num: 10
+
+language: fr
+
+next-page: nested-functions
+previous-page: mixin-class-composition
+---
+
+Les fonctions d'ordre supérieur prennent d'autres fonctions en paramètres ou retournent une fonction en résultat.
+C'est possible car les fonctions sont des valeurs de première classe en Scala.
+La terminologie peut devenir une peu confuse à ce point, et nous utilisons l'expression "fonction d'ordre supérieur" à la fois pour les méthodes et les fonctions qui prennent d'autres fonctions en paramètres ou retournent une fonction en résultat.
+
+Dans le monde du pur orienté objet, une bonne pratique est d'éviter d'exposer des méthodes paramétrées avec des fonctions qui pourraient exposer l'état interne de l'objet. Le fait d’exposer l'état interne de l'objet pourrait casser les invariants de l'objet lui-même ce qui violerait l'encapsulation.
+
+Un des exemples les plus communs est la fonction d'ordre supérieur `map` qui est diponible pour les collections en Scala.
+
+```scala mdoc
+val salaries = Seq(20000, 70000, 40000)
+val doubleSalary = (x: Int) => x * 2
+val newSalaries = salaries.map(doubleSalary) // List(40000, 140000, 80000)
+```
+
+`doubleSalary` est une fonction qui prend un seul entier, `x` et retourne `x * 2`. La partie à gauche de la flèche `=>` est la liste de paramètres, et la valeur de l'expression à droite est ce qui est retourné. Sur la ligne 3, la fonction `doubleSalary` est appliquée à chaque élément dans la liste des salariés.
+
+Pour réduire le code, nous pouvons faire une fonction anonyme et la passer directement en argument de `map` :
+
+```scala:nest
+val salaries = Seq(20000, 70000, 40000)
+val newSalaries = salaries.map(x => x * 2) // List(40000, 140000, 80000)
+```
+
+Notez que `x` n'est pas déclaré comme un `Int` dans l'exemple ci-dessus. C'est parce que le compilateur peut inférrer le type en se basant sur le type que méthode `map` attend. (voir [Currying](/tour/multiple-parameter-lists.html)). Une autre façon d'écrire le même morceau de code encore plus idiomatique serait :
+
+```scala mdoc:nest
+val salaries = Seq(20000, 70000, 40000)
+val newSalaries = salaries.map(_ * 2)
+```
+
+Sachant que le compilateur Scala sait déjà quel est le type des paramètres (un seul `Int`), vous pouvez fournir uniquement la partie de droite de la fonction.
+La seule contrepartie c'est que vous devez utiliser `_` à la place du nom du paramètre (c'était `x` dans l'exemple précédent).
+
+## Convertir les méthodes en fonctions
+
+Il est aussi possible de passer des méthodes comme arguments aux fonctions d'ordre supérieur, parce que le compilateur Scala va convertir la méthode en fonction.
+
+```scala mdoc
+case class WeeklyWeatherForecast(temperatures: Seq[Double]) {
+
+ private def convertCtoF(temp: Double) = temp * 1.8 + 32
+
+ def forecastInFahrenheit: Seq[Double] = temperatures.map(convertCtoF) // <-- passing the method convertCtoF
+}
+```
+
+Ici la méthode `convertCtoF` est passée à la fonction d'ordre supérieur `map`. C'est possible car le compilateur convertit `convertCtoF` vers la fonction `x => convertCtoF(x)` (note : `x` sera un nom généré qui sera garanti d'être unique dans le scope).
+
+## Les fonction qui acceptent des fonctions
+
+Une raison d'utiliser les fonctions d'ordre supérieur est de réduire le code redondant. Suposons que vous souhaitez des méthodes qui augmentent le salaire de quelqu'un en fonction de différents facteurs. Sans créer de fonction d'ordre supérieur, cela ressemblerait à ça :
+
+```scala mdoc
+object SalaryRaiser {
+
+ def smallPromotion(salaries: List[Double]): List[Double] =
+ salaries.map(salary => salary * 1.1)
+
+ def greatPromotion(salaries: List[Double]): List[Double] =
+ salaries.map(salary => salary * math.log(salary))
+
+ def hugePromotion(salaries: List[Double]): List[Double] =
+ salaries.map(salary => salary * salary)
+}
+```
+
+Notez comment chacunes de ces trois méthodes ne changent que par le facteur de multiplication.
+Pour simplifier, vous pouvez extraire le code répété dans une fonction d'ordre supérieur comme ceci :
+
+```scala mdoc:nest
+object SalaryRaiser {
+
+ private def promotion(salaries: List[Double], promotionFunction: Double => Double): List[Double] =
+ salaries.map(promotionFunction)
+
+ def smallPromotion(salaries: List[Double]): List[Double] =
+ promotion(salaries, salary => salary * 1.1)
+
+ def greatPromotion(salaries: List[Double]): List[Double] =
+ promotion(salaries, salary => salary * math.log(salary))
+
+ def hugePromotion(salaries: List[Double]): List[Double] =
+ promotion(salaries, salary => salary * salary)
+}
+```
+
+La nouvelle méthode, `promotion`, prend les salaires plus une fonction du type `Double => Double` (càd. une fonction qui prend un Double et retourne un Double) et retourne le produit.
+
+Les méthodes et les fonctions expriment généralement des comportements ou des transformations de données, donc avoir des fonctions qui composent en se basant sur d'autres fonctions peut aider à construire des mécanismes génériques. Ces opérations génériques reportent le verrouillage de l'intégralité du comportement de l'opération, donnant aux clients un moyen de contrôler ou de personnaliser davantage certaines parties de l'opération elle-même.
+
+## Les fonctions qui retournent des fonctions
+
+Il y a certains cas ou vous voulez générer une fonction. Voici un exemple de méthode qui retourne une fonction.
+
+```scala mdoc
+def urlBuilder(ssl: Boolean, domainName: String): (String, String) => String = {
+ val schema = if (ssl) "https://" else "http://"
+ (endpoint: String, query: String) => s"$schema$domainName/$endpoint?$query"
+}
+
+val domainName = "www.example.com"
+def getURL = urlBuilder(ssl=true, domainName)
+val endpoint = "users"
+val query = "id=1"
+val url = getURL(endpoint, query) // "https://www.example.com/users?id=1": String
+```
+
+Notez le type de retour de urlBuilder `(String, String) => String`. Cela veut dire que la fonction anonyme retournée prend deux Strings et retourne une String. Dans ce cas, la fonction anonyme retournée est `(endpoint: String, query: String) => s"https://www.example.com/$endpoint?$query"`
+
+Traduit par Antoine Pointeau.
\ No newline at end of file
diff --git a/_fr/tour/implicit-conversions.md b/_fr/tour/implicit-conversions.md
new file mode 100644
index 0000000000..1030827e4b
--- /dev/null
+++ b/_fr/tour/implicit-conversions.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Implicit Conversions
+partof: scala-tour
+
+num: 25
+
+language: fr
+
+next-page: polymorphic-methods
+previous-page: implicit-parameters
+---
diff --git a/_fr/tour/implicit-parameters.md b/_fr/tour/implicit-parameters.md
new file mode 100644
index 0000000000..236dd136f5
--- /dev/null
+++ b/_fr/tour/implicit-parameters.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Implicit Parameters
+partof: scala-tour
+
+num: 24
+
+language: fr
+
+next-page: implicit-conversions
+previous-page: self-types
+---
diff --git a/_fr/tour/inner-classes.md b/_fr/tour/inner-classes.md
new file mode 100644
index 0000000000..a5df305ce5
--- /dev/null
+++ b/_fr/tour/inner-classes.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Inner Classes
+partof: scala-tour
+
+num: 20
+
+language: fr
+
+next-page: abstract-type-members
+previous-page: lower-type-bounds
+---
diff --git a/_fr/tour/lower-type-bounds.md b/_fr/tour/lower-type-bounds.md
new file mode 100644
index 0000000000..eb6ffb785c
--- /dev/null
+++ b/_fr/tour/lower-type-bounds.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Lower Type Bounds
+partof: scala-tour
+
+num: 19
+
+language: fr
+
+next-page: inner-classes
+previous-page: upper-type-bounds
+---
diff --git a/_fr/tour/mixin-class-composition.md b/_fr/tour/mixin-class-composition.md
new file mode 100644
index 0000000000..8d1b823c11
--- /dev/null
+++ b/_fr/tour/mixin-class-composition.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Class Composition with Mixins
+partof: scala-tour
+
+num: 6
+
+language: fr
+
+next-page: higher-order-functions
+previous-page: tuples
+---
diff --git a/_fr/tour/multiple-parameter-lists.md b/_fr/tour/multiple-parameter-lists.md
new file mode 100644
index 0000000000..476e918cc1
--- /dev/null
+++ b/_fr/tour/multiple-parameter-lists.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Multiple Parameter Lists (Currying)
+partof: scala-tour
+
+num: 9
+
+language: fr
+
+next-page: case-classes
+previous-page: nested-functions
+---
diff --git a/_fr/tour/named-arguments.md b/_fr/tour/named-arguments.md
new file mode 100644
index 0000000000..fec11428a3
--- /dev/null
+++ b/_fr/tour/named-arguments.md
@@ -0,0 +1,34 @@
+---
+layout: tour
+title: Named Arguments
+partof: scala-tour
+
+num: 6
+
+language: fr
+
+next-page: traits
+previous-page: default-parameter-values
+---
+
+En appelant des méthodes, vous pouvez nommer leurs arguments comme ceci :
+
+```scala mdoc
+def printName(first: String, last: String): Unit = {
+ println(first + " " + last)
+}
+
+printName("John", "Smith") // Prints "John Smith"
+printName(first = "John", last = "Smith") // Prints "John Smith"
+printName(last = "Smith", first = "John") // Prints "John Smith"
+```
+
+Notez comment l'ordre des arguments nommés peut être réarrangé. Cependant, si certains arguments sont nommés et d'autres non, les arguments non nommés doivent venir en premier et suivrent l'ordre de leurs paramètres dans la signature de la méthode.
+
+```scala mdoc:fail
+printName(last = "Smith", "john") // erreur: argument positionnel après un argument nommé
+```
+
+Les arguments nommés fonctionnent avec les appels de méthodes Java, mais seulement si la librairie Java en question a été compilée avec `-parameters`.
+
+Traduction par Antoine Pointeau.
\ No newline at end of file
diff --git a/_fr/tour/nested-functions.md b/_fr/tour/nested-functions.md
new file mode 100644
index 0000000000..f92045364f
--- /dev/null
+++ b/_fr/tour/nested-functions.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Nested Methods
+partof: scala-tour
+
+num: 8
+
+language: fr
+
+next-page: multiple-parameter-lists
+previous-page: higher-order-functions
+---
diff --git a/_fr/tour/operators.md b/_fr/tour/operators.md
new file mode 100644
index 0000000000..59c697727e
--- /dev/null
+++ b/_fr/tour/operators.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Operators
+partof: scala-tour
+
+num: 28
+
+language: fr
+
+next-page: by-name-parameters
+previous-page: type-inference
+---
diff --git a/_fr/tour/package-objects.md b/_fr/tour/package-objects.md
new file mode 100644
index 0000000000..80cfb5e055
--- /dev/null
+++ b/_fr/tour/package-objects.md
@@ -0,0 +1,9 @@
+---
+layout: tour
+title: Package Objects
+language: fr
+partof: scala-tour
+
+num: 36
+previous-page: packages-and-imports
+---
diff --git a/_fr/tour/packages-and-imports.md b/_fr/tour/packages-and-imports.md
new file mode 100644
index 0000000000..8edac3b01c
--- /dev/null
+++ b/_fr/tour/packages-and-imports.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Packages and Imports
+partof: scala-tour
+
+num: 33
+
+language: fr
+
+previous-page: named-arguments
+next-page: package-objects
+---
diff --git a/_fr/tour/pattern-matching.md b/_fr/tour/pattern-matching.md
new file mode 100644
index 0000000000..1cd3731b9a
--- /dev/null
+++ b/_fr/tour/pattern-matching.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Pattern Matching
+partof: scala-tour
+
+num: 11
+
+language: fr
+
+next-page: singleton-objects
+previous-page: case-classes
+---
diff --git a/_fr/tour/polymorphic-methods.md b/_fr/tour/polymorphic-methods.md
new file mode 100644
index 0000000000..6375d54957
--- /dev/null
+++ b/_fr/tour/polymorphic-methods.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Polymorphic Methods
+partof: scala-tour
+
+num: 26
+
+language: fr
+
+next-page: type-inference
+previous-page: implicit-conversions
+---
diff --git a/_fr/tour/regular-expression-patterns.md b/_fr/tour/regular-expression-patterns.md
new file mode 100644
index 0000000000..253da8efa6
--- /dev/null
+++ b/_fr/tour/regular-expression-patterns.md
@@ -0,0 +1,63 @@
+---
+layout: tour
+title: Regular Expression Patterns
+partof: scala-tour
+
+num: 17
+
+language: fr
+
+next-page: extractor-objects
+previous-page: singleton-objects
+---
+
+Les expressions régulières sont des chaînes de caractères qui peuvent être utilisées pour trouver des motifs (ou l'absence de motif) dans un texte. Toutes les chaînes de caractères peuvent être converties en expressions régulières en utilisant la méthode `.r`.
+
+```scala mdoc
+import scala.util.matching.Regex
+
+val numberPattern: Regex = "[0-9]".r
+
+numberPattern.findFirstMatchIn("awesomepassword") match {
+ case Some(_) => println("Password OK")
+ case None => println("Password must contain a number")
+}
+```
+
+Dans l'exemple ci-dessus, `numberPattern` est une `Regex` (EXpression REGulière) que nous utilisons pour vérifier que le mot de passe contient un nombre.
+
+Vous pouvez aussi faire des recherches de groupes d'expressions régulières en utilisant les parenthèses.
+
+```scala mdoc
+import scala.util.matching.Regex
+
+val keyValPattern: Regex = "([0-9a-zA-Z- ]+): ([0-9a-zA-Z-#()/. ]+)".r
+
+val input: String =
+ """background-color: #A03300;
+ |background-image: url(img/header100.png);
+ |background-position: top center;
+ |background-repeat: repeat-x;
+ |background-size: 2160px 108px;
+ |margin: 0;
+ |height: 108px;
+ |width: 100%;""".stripMargin
+
+for (patternMatch <- keyValPattern.findAllMatchIn(input))
+ println(s"key: ${patternMatch.group(1)} value: ${patternMatch.group(2)}")
+```
+
+Ici nous analysons les clefs et les valeurs d'une chaîne de caractère. Chaque correspondance a un groupe de sous-correspondances. Voici le résultat :
+
+```
+key: background-color value: #A03300
+key: background-image value: url(img/header100.png)
+key: background-position value: top center
+key: background-repeat value: repeat-x
+key: background-size value: 2160px 108px
+key: margin value: 0
+key: height value: 108px
+key: width value: 100
+```
+
+Traduit par Antoine Pointeau.
\ No newline at end of file
diff --git a/_fr/tour/self-types.md b/_fr/tour/self-types.md
new file mode 100644
index 0000000000..9d82783417
--- /dev/null
+++ b/_fr/tour/self-types.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Self-types
+partof: scala-tour
+
+num: 23
+
+language: fr
+
+next-page: implicit-parameters
+previous-page: compound-types
+---
diff --git a/_fr/tour/singleton-objects.md b/_fr/tour/singleton-objects.md
new file mode 100644
index 0000000000..073dfaf5ec
--- /dev/null
+++ b/_fr/tour/singleton-objects.md
@@ -0,0 +1,120 @@
+---
+layout: tour
+title: Singleton Objects
+partof: scala-tour
+
+num: 15
+
+language: fr
+
+next-page: regular-expression-patterns
+previous-page: pattern-matching
+---
+
+Un objet est une classe qui a exactement une instance. Il est créé de façon paresseuse au moment où il est référencé, comme une valeur paresseuse `lazy val`.
+
+En tant que valeur de premier niveau, un objet est un singleton.
+
+En tant que membre d'une classe englobante ou en tant que valeur locale, il se comporte exactement comme une `lazy val`.
+
+# Définir un objet singleton
+
+Un objet est une valeur. La définition d'un objet ressemble a une classe, mais utilise le mot clef `object` :
+
+```scala mdoc
+object Box
+```
+
+Voici un exemple d'un objet avec une méthode :
+
+```
+package logging
+
+object Logger {
+ def info(message: String): Unit = println(s"INFO: $message")
+}
+```
+
+La méthode `info` peut être importée depuis n'importe où dans le programme. Créer des méthodes utilitaires, comme celle-ci, est un cas d'usage commun pour les objets singleton.
+
+Regardons comment utiliser `info` dans un autre package :
+
+```
+import logging.Logger.info
+
+class Project(name: String, daysToComplete: Int)
+
+class Test {
+ val project1 = new Project("TPS Reports", 1)
+ val project2 = new Project("Website redesign", 5)
+ info("Created projects") // Prints "INFO: Created projects"
+}
+```
+
+La méthode `info` est visible grâce à l'import, `import logging.Logger.info`. Les imports ont besoin d'un chemin d'accès stable aux ressources, et un objet est un chemin stable.
+
+Note : Si un `objet` est encapsulé dans une autre classe ou un autre objet, alors l'objet est dépendant du chemin d'accès, comme les autres membres. Cela veut dire, par exemple, que si on prend 2 types de boissons, `class Milk` et `class OrangeJuice`, un membre de classe `object NutritionInfo` est dépendant de son instance d'encapsulation. `milk.NutritionInfo` est complètement différent de `oj.NutritionInfo`.
+
+## Les objets compagnons
+
+Un objet avec le même nom qu'une classe est appelé un _objet compagnon_. Inversement, la classe se nomme la _classe compagnon_ de l'objet. Une classe ou un objet compagnon peut accéder aux membres privés de son compagnon. L'objet compagnon est utile pour les méthodes et les valeurs qui ne sont pas spécifiques aux instances de la classe compagnon.
+
+```
+import scala.math._
+
+case class Circle(radius: Double) {
+ import Circle._
+ def area: Double = calculateArea(radius)
+}
+
+object Circle {
+ private def calculateArea(radius: Double): Double = Pi * pow(radius, 2.0)
+}
+
+val circle1 = Circle(5.0)
+
+circle1.area
+```
+
+La classe `class Circle` a un membre `area` qui est spécifique à chaque instance, et un singleton `object Circle` qui a une méthode `calculateArea` qui est disponible pour chaque instance.
+
+L'objet compagnon peut aussi contenir des méthodes de fabrique (_factory_) :
+
+```scala mdoc
+class Email(val username: String, val domainName: String)
+
+object Email {
+ def fromString(emailString: String): Option[Email] = {
+ emailString.split('@') match {
+ case Array(a, b) => Some(new Email(a, b))
+ case _ => None
+ }
+ }
+}
+
+val scalaCenterEmail = Email.fromString("scala.center@epfl.ch")
+scalaCenterEmail match {
+ case Some(email) => println(
+ s"""Registered an email
+ |Username: ${email.username}
+ |Domain name: ${email.domainName}
+ """.stripMargin)
+ case None => println("Error: could not parse email")
+}
+```
+
+L'objet `object Email` contient une méthode de fabrique `fromString` qui créé une instance de `Email` depuis une chaîne de caractères. L'instance est retournée en tant que `Option[Email]` pour gérer le cas des erreurs de syntaxe.
+
+Note : Si une classe ou un objet a un compagnon, tous deux doivent être définis dans le même fichier. Pour définir des compagnons dans le REPL, tous deux doivent être définis sur la même ligne ou définis en mode `:paste`.
+
+## Notes pour les programmeurs Java
+
+Les membres `static` en Java sont modélisés comme des membres ordinaires d'un objet compagnon en Scala.
+
+Lorsqu'on utilise un objet compagnon depuis du code Java, ses membres sont définis dans la classe compagnon avec le modificateur `static`. Cela s'appelle le _static forwarding_. Cela se produit même si vous n'avez pas défini de classe compagnon vous-même.
+
+## Plus d'informations
+
+* Apprenez-en plus sur les objets compagnons dans le [Scala Book](/overviews/scala-book/companion-objects.html)
+
+Traduit par Antoine Pointeau.
diff --git a/_fr/tour/tour-of-scala.md b/_fr/tour/tour-of-scala.md
new file mode 100644
index 0000000000..f5d0f5d20a
--- /dev/null
+++ b/_fr/tour/tour-of-scala.md
@@ -0,0 +1,90 @@
+---
+layout: tour
+title: Introduction
+partof: scala-tour
+
+num: 1
+language: fr
+next-page: basics
+
+---
+
+## Bienvenue au tour
+Ce tour contient une introduction morceaux par morceaux aux fonctionnalités les plus fréquemment
+utilisées en Scala. Il est adressé aux novices de Scala.
+
+Ceci est un bref tour du language, non pas un tutoriel complet.
+Si vous recherchez un guide plus détaillé, il est préférable d'opter pour [un livre](/books.html) ou de suivre
+[un cours en ligne](/online-courses.html).
+
+## Qu'est-ce que le Scala ?
+Scala est un langage de programmation à multiples paradigmes désigné pour exprimer des motifs de programmation communs de
+façon concise, élégante et robuste. Il intègre sans problème les fonctionnalités des langages orientés objet et des
+langages fonctionnels.
+
+## Scala est orienté objet ##
+Scala est un langage purement orienté objet dans le sens où [toute valeur est un objet](unified-types.html).
+Les types et les comportements de ces objets sont décrits par des [classes](classes.html) et des trait [traits](traits.html).
+Les classes peuvent être étendues à travers des sous-classes et grâce à un système flexible de [composition de classes](mixin-class-composition.html).
+
+## Scala est fonctionnel ##
+Scala est également un langage fonctionnel dans le sen où [toute fonction est une valeur](unified-types.html).
+Scala propose une [syntaxe légère](basics.html) pour définir des fonctions anonymes, supporte des
+[fonctions de haut niveau](higher-order-functions.html), autorise les fonctions [imbriquées](nested-functions.html) et
+supporte le [currying](multiple-parameter-lists.html).
+Les [case class](case-classes.html) de Scala et leur système intégré de [reconnaissance de motifs](pattern-matching.html)
+permettent de construire des types algébriques utilisés dans de nombreux langages de programmation.
+Les [objets singleton](singleton-objects.html) fournissent une façon pratique de regrouper des fonctions qui ne sont pas
+membres d'une classe.
+
+De plus, la notion de reconnaissance de motifs de Scala s'étend naturellement au
+[traitement des données XML](https://github.com/scala/scala-xml/wiki/XML-Processing) avec l'aide des
+[patrons d'expressions régulières](regular-expression-patterns.html), grâce à une extension générale via des
+[objets extracteurs](extractor-objects.html). Dans ce contexte, les [for comprehensions](for-comprehensions.html) sont
+utiles pour formuler des requêtes. Ces fonctionnalités font de Scala un langage idéal pour développer des applications
+comme des services Web.
+
+## Scala est fortement typé ##
+A la compilation, le système de type expressif de Scala renforce l'utilisation des abstractions d'une manière
+sécurisée et cohérente. En particulier, ce système de type supporte :
+
+* Les [classes génériques](generic-classes.html)
+* Les [annotations variables](variances.html)
+* Les limites de type [supérieures](upper-type-bounds.html) and [inférieures](lower-type-bounds.html)
+* Les [classes internes](inner-classes.html) et les membres d'objets de [types abstraits](abstract-type-members.html)
+* Les [types composés](compound-types.html)
+* Les [auto-références explicitement typées](self-types.html)
+* Les [paramètres](implicit-parameters.html) et les [conversions](implicit-conversions.html) implicites
+* Les [méthodes polymorphiques](polymorphic-methods.html)
+
+L'[inférence de type](type-inference.html) signifie que l'utilisateur n'est pas obligé d'annoter son code avec des
+informations redondantes. Rassemblées, toutes ces fonctionnalités fournissent une base solide pour la ré-utilisation
+sécurisée d'abstractions de programmation et pour une extension sûre au niveau des types de programme.
+
+## Scala est extensible ##
+
+En pratique, le développement d'applications dans un domaine spécifique demande souvent des extensions de langage propre
+à ce domaine. Scala fournit une combinaison de mécaniques de langage unique qui rend simple l'ajout de nouvelles
+constructions de langage avec l'importation de nouvelles librairies.
+
+Dans beaucoup de cas, cela peut être fait sans utiliser des outils de méta-programmation, comme les macros.
+En voici quelques exemples :
+
+* Les [classes implicites](/overviews/core/implicit-classes.html) permettent d'ajouter des méthodes supplémentaires à des types existants.
+* L'[interpolation de String](/overviews/core/string-interpolation.html) est extensible par l'utilisateur avec des interpolateurs personnalisés.
+
+## Scala interagit ##
+
+Scala est conçu pour interagir proprement avec le populaire Java Runtime Environment (JRE). En particulier, l'interaction
+avec le langage de programmation orienté objet le plus populaire du moment, Java, est la plus transparente possible.
+Les nouvelles fonctionnalités Java comme les SAMs, les [lambdas](higher-order-functions.html), les [annotations](annotations.html),
+et les [classes génériques](generic-classes.html) ont des équivalents directs en Scala.
+
+Il existe des fonctionnalités Scala sans équivalent Java, comme les [valeurs par défaut](default-parameter-values.html) et les
+[paramètres nommés](named-arguments.html), qui se compilent d'une façon la plus proche de Java possible. Scala possède le
+même modèle de compilation que Java (compilation séparée, chargement dynamique des classes) et permet d'avoir accès à des
+milliers de librairies de haute qualité.
+
+## Bon tour !
+
+Merci de continuer à la [page suivante](basics.html) pour en savoir plus.
diff --git a/_fr/tour/traits.md b/_fr/tour/traits.md
new file mode 100644
index 0000000000..069648bb53
--- /dev/null
+++ b/_fr/tour/traits.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Traits
+partof: scala-tour
+
+num: 5
+
+language: fr
+
+next-page: tuples
+previous-page: classes
+---
diff --git a/_fr/tour/tuples.md b/_fr/tour/tuples.md
new file mode 100644
index 0000000000..edef97a6ca
--- /dev/null
+++ b/_fr/tour/tuples.md
@@ -0,0 +1,82 @@
+---
+layout: tour
+title: Tuples
+partof: scala-tour
+
+num: 8
+
+language: fr
+
+next-page: mixin-class-composition
+previous-page: traits
+---
+
+En Scala, un tuple est une valeur qui contient un nombre fixe d'éléments, chacun avec son propre type. Les tuples sont immuables.
+
+Les tuples sont notamment utiles pour retourner plusieurs valeurs depuis une méthode.
+
+Un tuple avec deux éléments peut être créé de la façon suivante :
+
+```scala mdoc
+val ingredient = ("Sugar" , 25)
+```
+
+Cela crée un tuple contenant un élément de type `String` et un élément de type `Int`.
+
+Le type inféré de `ingredient` est `(String, Int)`, qui est un raccourci pour `Tuple2[String, Int]`.
+
+Pour représenter les tuples, Scala utilise une série de classes : `Tuple2`, `Tuple3`, etc., jusqu'a `Tuple22`.
+Chaque classe a autant de paramètres de types qu'elle a d'éléments.
+
+## Accéder aux éléments
+
+Une des méthodes pour accéder aux éléments d'un tuple est par position. Les éléments sont nommés individuellement `_1`, `_2`, et ainsi de suite.
+
+```scala mdoc
+println(ingredient._1) // Sugar
+println(ingredient._2) // 25
+```
+
+## Pattern matching sur les tuples
+
+Un tuple peut aussi être décomposé en utilisant le pattern matching :
+
+```scala mdoc
+val (name, quantity) = ingredient
+println(name) // Sugar
+println(quantity) // 25
+```
+
+Ici le type inféré de `name` est `String` et le type inféré de `quantity` est `Int`.
+
+Voici un autre exemple de pattern-matching sur un tuple :
+
+```scala mdoc
+val planets =
+ List(("Mercury", 57.9), ("Venus", 108.2), ("Earth", 149.6),
+ ("Mars", 227.9), ("Jupiter", 778.3))
+planets.foreach {
+ case ("Earth", distance) =>
+ println(s"Our planet is $distance million kilometers from the sun")
+ case _ =>
+}
+```
+
+Ou, en décomposition dans un `for` :
+
+```scala mdoc
+val numPairs = List((2, 5), (3, -7), (20, 56))
+for ((a, b) <- numPairs) {
+ println(a * b)
+}
+```
+
+## Les tuples et les classes de cas
+
+Les utilisateurs trouvent parfois qu'il est difficile de choisir entre les tuples et les classes de cas. Les classes de cas ont des éléments nommés. Les noms peuvent améliorer la lisibilité de certains codes. Dans l'exemple ci-dessus avec planet, nous pourrions définir `case class Planet(name: String, distance: Double)` plutôt que d'utiliser les tuples.
+
+## Plus d'informations
+
+* Apprennez-en d'avantage sur les tuples dans [Scala Book](/overviews/scala-book/tuples.html)
+
+Traduction par Antoine Pointeau.
\ No newline at end of file
diff --git a/_fr/tour/type-inference.md b/_fr/tour/type-inference.md
new file mode 100644
index 0000000000..019ed21ef5
--- /dev/null
+++ b/_fr/tour/type-inference.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Type Inference
+partof: scala-tour
+
+num: 27
+
+language: fr
+
+next-page: operators
+previous-page: polymorphic-methods
+---
diff --git a/_fr/tour/unified-types.md b/_fr/tour/unified-types.md
new file mode 100644
index 0000000000..6ecf013319
--- /dev/null
+++ b/_fr/tour/unified-types.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Unified Types
+partof: scala-tour
+
+num: 3
+
+language: fr
+
+next-page: classes
+previous-page: basics
+---
diff --git a/_fr/tour/upper-type-bounds.md b/_fr/tour/upper-type-bounds.md
new file mode 100644
index 0000000000..f47c6a4e30
--- /dev/null
+++ b/_fr/tour/upper-type-bounds.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Upper Type Bounds
+partof: scala-tour
+
+num: 18
+
+language: fr
+
+next-page: lower-type-bounds
+previous-page: variances
+---
diff --git a/_fr/tour/variances.md b/_fr/tour/variances.md
new file mode 100644
index 0000000000..5f535d303b
--- /dev/null
+++ b/_fr/tour/variances.md
@@ -0,0 +1,12 @@
+---
+layout: tour
+title: Variance
+partof: scala-tour
+
+num: 17
+
+language: fr
+
+next-page: upper-type-bounds
+previous-page: generic-classes
+---
diff --git a/_fr/tutorials/scala-for-java-programmers.md b/_fr/tutorials/scala-for-java-programmers.md
new file mode 100644
index 0000000000..0b9d3ffa63
--- /dev/null
+++ b/_fr/tutorials/scala-for-java-programmers.md
@@ -0,0 +1,667 @@
+---
+layout: singlepage-overview
+title: Tutoriel Scala pour développeurs Java
+
+partof: scala-for-java-programmers
+language: fr
+---
+
+Par Michel Schinz and Philipp Haller.
+
+Traduction et arrangements par Agnès Maury.
+
+## Introduction
+
+Ce document présente une introduction rapide au langage Scala et à son compilateur.
+Il est destiné aux personnes ayant une expérience de programmation et qui souhaitent
+un aperçu de ce qu'ils peuvent faire avec Scala. On part du principe que le lecteur possède
+des connaissances de base sur la programmation orientée objet, particulièrement sur Java.
+
+
+## Un premier exemple
+
+Commençons par écrire le célèbre programme *Hello world*.
+Bien que simple, il permet de découvrir plusieurs fonctionnalités du language
+avec peu de connaissance préalable de Scala. Voilà à quoi il ressemble :
+
+ object HelloWorld {
+ def main(args: Array[String]): Unit = {
+ println("Hello, world!")
+ }
+ }
+
+La structure de ce programme devrait être familière pour les développeurs Java :
+il consiste en une méthode appelée `main` qui prend les arguments de la ligne de commande,
+une array de String, comme paramètre ; le corps de cette méthode consiste en un simple appel de la méthode
+prédéfinie `println` avec le salut amical comme argument. Cette méthode `main` ne retourne pas de valeur.
+Pourtant, son type de retour est déclaré comme `Unit`.
+
+Ce qui est moins familier pour les développeurs Java est la déclaration `object` qui contient la méthode
+`main`. Une telle déclaration introduit ce qui est communément connu comme un *objet singleton*, qui est une classe
+avec une seule instance. La déclaration ci-dessus déclare à la fois une classe nommée `HelloWorld`
+et une instance de cette classe, aussi nommée `HelloWorld`. Cette instance est créée sur demande, c'est-à-dire,
+la première fois qu'elle est utilisée.
+
+Le lecteur avisé a pu remarquer que la méthode `main` n'est pas déclarée en tant que `static`.
+C'est parce que les membres statiques (membres ou champs) n'existent pas en Scala. Plutôt que de définir des
+membres statiques, le développeur Scala déclare ces membres dans un objet singleton.
+
+### Compiler l'exemple
+
+Pour compiler cet exemple, nous utilisons `scalac`, le compilateur Scala.
+`scalac` fonctionne comme la plupart des compilateurs : il prend comme argument un fichier source,
+potentiellement certaines options, et produit un ou plusieurs fichiers objets.
+Les fichiers objets produits sont des fichiers classes de Java classiques.
+
+Si nous sauvegardons le programme ci-dessus dans un fichier appelé `HelloWorld.scala`,
+nous pouvons le compiler en exécutant la commande suivante (le symbole supérieur `>` représente
+l'invité de commandes et ne doit pas être écrit) :
+
+ > scalac HelloWorld.scala
+
+Cette commande va générer un certain nombre de fichiers class dans le répertoire courant.
+L'un d'entre eux s'appellera `HelloWorld.class` et contiendra une classe qui pourra être directement exécutée
+en utilisant la commande `scala`, comme décrit dans la section suivante.
+
+### Exécuter l'exemple
+
+Une fois compilé, le programme Scala peut être exécuté en utilisant la commande `scala`.
+Son utilisation est très similaire à la commande `java` utilisée pour exécuter les programmes Java,
+et qui accepte les mêmes options. L'exemple ci-dessus peut être exécuté en utilisant la commande suivante,
+ce qui produit le résultat attendu :
+
+ > scala -classpath . HelloWorld
+
+ Hello, world!
+
+## Interaction avec Java
+
+L'une des forces du Scala est qu'il rend très facile l'interaction avec le code Java.
+Toutes les classes du paquet `java.lang` sont importées par défaut, alors que les autres
+doivent être importées explicitement.
+
+Prenons l'exemple suivant. Nous voulons obtenir et formater la date actuelle
+par rapport aux conventions utilisées dans un pays spécifique, par exemple la France.
+
+Les librairies de classes Java définissent des classes utilitaires très puissantes, comme `Date`
+et `DateFormat`. Comme Scala interagit avec Java, il n'y a pas besoin de ré-implémenter ces classes en Scala
+--nous pouvons simplement importer les classes des paquets correspondants de Java :
+
+ import java.util.{Date, Locale}
+ import java.text.DateFormat._
+
+ object DateFrancaise {
+ def main(args: Array[String]): Unit = {
+ val maintenant = new Date
+ val df = getDateInstance(LONG, Locale.FRANCE)
+ println(df format maintenant)
+ }
+ }
+
+Les déclarations d'import de Scala sont très similaires à celle de Java, cependant,
+elles sont bien plus puissantes. Plusieurs classes peuvent être importées du même paquet en les plaçant
+dans des accolades comme démontré dans la première ligne. Une autre différence notable est de pouvoir
+importer tous les noms d'un paquet ou d'une classe en utilisant le symbole underscore (`_`) au lieu de
+l'astérisque (`*`). C'est parce que l'astérisque est un identifiant valide en Scala (par exemple pour
+un nom de méthode), comme nous le verrons plus tard.
+
+Par conséquent, la déclaration d'importation dans la seconde ligne importe tous les membres de la classe
+`DateFormat`. Cela rend la méthode statique `getDateInstance` et le champ statique `LONG`
+directement visibles.
+
+Dans la méthode `main`, nous avons tout d'abord créé une instance de la classe Java `Date`
+qui contient par défaut la date actuelle. Ensuite, nous définissons un format de date en utilisant la
+méthode statique `getDateInstance` que nous avons importée précédemment. Enfin, nous imprimons
+la date actuelle selon l'instance de `DateFormat` localisée. Cette dernière ligne montre une
+propriété intéressante de la syntaxe Scala. Les méthodes qui ne prennent en entrée qu'un seul argument
+peuvent être utilisées avec une syntaxe infixe. C'est-à-dire que l'expression
+
+ df format maintenant
+
+est juste une autre façon moins verbeuse d'écrire l'expression
+
+ df.format(maintenant)
+
+Cela peut paraître comme un détail syntaxique mineur, mais il entraîne des conséquences importantes,
+dont l'une va être explorée dans la section suivante.
+
+Pour conclure cette section sur l'intégration avec Java, il faut noter qu'il est possible
+d'hériter de classes Java et d'implémenter des interfaces Java directement en Scala.
+
+## Tout est objet
+
+Scala est un langage purement orienté objet dans le sens où *tout* est un objet,
+y compris les nombres ou les fonctions. Cela diffère du Java dans cet aspect, car Java
+distingue les types primitifs (comme `boolean` et `int`) des types référentiels.
+
+### Les nombres sont des objets
+
+Étant donné que les nombres sont des objets, ils ont aussi des méthodes.
+De fait, une expression arithmétique comme la suivante :
+
+ 1 + 2 * 3 / x
+
+consiste exclusivement en des appels de méthodes, parce qu'il est équivalent à l'expression
+suivante, comme nous l'avons vu dans la section précédente :
+
+ 1.+(2.*(3)./(x)
+
+Cela veut aussi dire que `+`, `*`, etc. sont des identifiants valides en Scala.
+
+### Les fonctions sont des objets
+
+Les fonctions sont aussi des objets en Scala. C'est pourquoi il est possible de passer
+des fonctions en arguments, de les stocker dans des variables et de les retourner depuis d'autres
+fonctions. Cette capacité à manipuler les fonctions en tant que valeurs est l'une des
+pierres angulaires d'un paradigme de programmation très intéressant nommé *programmation fonctionnelle*.
+
+Pour illustrer à quel point il est peut être utile d'utiliser des fonctions en tant que valeurs,
+considérons une fonction minuteur qui vise à performer une action toutes les secondes. Comment faire
+pour passer au minuteur une action à performer ? En toute logique, comme une fonction. Ce concept de
+passer une fonction devrait être familier à beaucoup de développeurs : il est souvent utilisé dans
+le code d'interface utilisateur pour enregistrer des fonctions de rappel qui sont invoquées lorsque
+certains évènements se produisent.
+
+Dans le programme suivant, la fonction minuteur est appelée `uneFoisParSeconde` et prend comme argument
+une fonction de rappel. Le type de cette fonction est écrit `() => Unit`. C'est le type de toutes les
+fonctions qui ne prennent aucun argument et ne renvoie rien (le type `Unit` est similaire à `void` en C/C++).
+La principale fonction de ce programme est d'appeler la fonction minuteur avec une fonction de rappel
+qui imprime une phrase dans le terminal. Dans d'autres termes, ce programme imprime à l'infini la phrase
+"le temps passe comme une flèche".
+
+ object Minuteur {
+ def uneFoisParSeconde(retour: () => Unit): Unit = {
+ while (true) {
+ retour()
+ Thread sleep 1000
+ }
+ }
+
+ def leTempsPasse(): Unit = {
+ println("le temps passe comme une flèche")
+ }
+
+ def main(args: Array[String]): Unit = {
+ uneFoisParSeconde(leTempsPasse)
+ }
+ }
+
+Notez que pour imprimer la String, nous utilisons la méthode prédéfinie `println` au lieu
+d'utiliser celle du paquet `System.out`.
+
+#### Fonctions anonymes
+
+Bien que ce programme soit facile à comprendre, il peut être affiné un peu plus.
+Premièrement, notez que la fonction `leTempsPasse` est définie uniquement dans le but d'être
+passée plus tard dans la fonction `uneFoisParSeconde`. Devoir nommer cette fonction qui ne va
+être utilisée qu'une fois peut sembler superflu et il serait plus agréable de pouvoir construire
+cette fonction juste au moment où elle est passée à `uneFoisParSeconde`. C'est possible en Scala
+en utilisant des *fonctions anonymes*, ce qui correspond exactement à ça : des fonctions sans nom.
+La version revisitée de notre programme minuteur en utilisant une fonction anonyme à la place de
+*leTempsPasse* ressemble à ça :
+
+ object MinuteurAnonyme {
+ def uneFoisParSeconde(retour: () => Unit): Unit = {
+ while (true) {
+ retour()
+ Thread sleep 1000
+ }
+ }
+
+ def main(args: Array[String]): Unit = {
+ uneFoisParSeconde(
+ () => println("le temps passe comme une flèche")
+ )
+ }
+ }
+
+La présence d'une fonction anonyme dans cet exemple est reconnaissable par la flèche pointant à droite
+`=>` qui sépare la liste des arguments de la fonction de son corps. Dans cet exemple, la liste des
+arguments est vide, comme en témoigne la paire de parenthèses vide à gauche de la flèche. Le corps
+de cette fonction est le même que celui de `leTempsPasse` décrit plus haut.
+
+## Classes
+
+Comme nous l'avons vu plus tôt, Scala est un langage orienté objet et de ce fait, possède le concept de classe
+(pour être plus exact, il existe certains langages orientés objet qui ne possèdent pas le concept de classe
+mais Scala n'en fait pas partie). Les classes en Scala sont déclarées en utilisant une syntaxe proche de
+celle de Java. Une différence notable est que les classes en Scala peuvent avoir des paramètres.
+Ceci est illustré dans la définition suivante des nombres complexes.
+
+ class Complexe(reel: Double, imaginaire: Double) {
+ def re() = reel
+ def im() = imaginaire
+ }
+
+La classe `Complexe` prend en entrée deux arguments : la partie réelle et la partie imaginaire du
+nombre complexe. Ces arguments peuvent être passés lors de la création d'une instance de `Complexe` comme
+ceci :
+
+ new Complexe(1.5, 2.3)
+
+La classe contient deux méthodes, appelées `re` et `im` qui donnent accès à ces deux parties.
+
+Il faut noter que le type de retour de ces méthodes n'est pas explicitement donné. Il sera inféré
+automatiquement par le compilateur, qui regarde la partie droite de ces méthodes et en déduit que chacune
+de ces fonctions renvoie une valeur de type `Double`.
+
+Le compilateur n'est pas toujours capable d'inférer des types comme il le fait ici et il n'y a
+malheureusement aucune règle simple pour savoir dans quel cas il est capable de le faire. En pratique,
+ce n'est pas généralement un problème car le compilateur se plaint quand il n'est pas capable d'inférer
+un type qui n'a pas été donné explicitement. Une règle simple que les développeurs débutant en Scala
+devraient suivre est d'essayer d'omettre les déclarations de type qui semblent être faciles à
+déduire et voir si le compilateur ne renvoie pas d'erreur. Après quelque temps, le développeur devrait
+avoir une bonne idée de quand il peut omettre les types et quand il faut les spécifier explicitement.
+
+### Les méthodes sans arguments
+
+Un petit problème des méthodes `re` et `im` est qu'il faut mettre une paire de parenthèses vides après
+leur nom pour les appeler, comme démontré dans l'exemple suivant :
+
+ object NombresComplexes {
+ def main(args: Array[String]): Unit = {
+ val c = new Complexe(1.2, 3.4)
+ println("partie imaginaire : " + c.im())
+ }
+ }
+
+Il serait plus agréable de pouvoir accéder à la partie réelle et imaginaire comme si elles étaient des
+champs, sans ajouter une paire de parenthèses vides. C'est parfaitement faisable en Scala, simplement en
+les définissant comme des méthodes *sans argument*. De telles méthodes diffèrent des méthodes avec
+aucun argument : elles n'ont pas de parenthèses après leur nom, que ce soit dans leur déclaration
+ou lors de leur utilisation. Notre classe `Complexe` peut être réécrite de cette façon :
+
+ class Complexe(reel: Double, imaginaire: Double) {
+ def re = reel
+ def im = imaginaire
+ }
+
+
+### Héritage et redéfinition
+
+Toutes les classes en Scala héritent d'une super classe. Quand aucune super classe n'est spécifiée,
+comme dans l'exemple `Complexe` de la section précédente, la classe `scala.AnyRef` est utilisée
+implicitement.
+
+Il est possible de redéfinir les méthodes héritées d'une super classe en Scala. Cependant, il est
+obligatoire de spécifier explicitement qu'une méthode en redéfinit une autre en utilisant le
+modificateur `override` dans le but d'éviter les redéfinitions accidentelles. Dans notre exemple,
+la classe `Complexe` peut être enrichie avec une redéfinition de la méthode `toString` héritée
+de la classe `Object`.
+
+ class Complexe(reel: Double, imaginaire: Double) {
+ def re() = reel
+ def im() = imaginaire
+ override def toString() = "" + re + (if (im >= 0) "+" + im + "i" else "")
+ }
+
+Nous pouvons alors appeler la méthode `toString` redéfinie comme ci-dessus.
+
+ object NombresComplexes {
+ def main(args: Array[String]): Unit = {
+ val c = new Complexe(1.2, 3.4)
+ println("toString() redéfinie : " + c.toString)
+ }
+ }
+
+## Les case class et le pattern matching
+
+L'arbre est un type de structure de données qui revient souvent.
+Par exemple, les interpréteurs et les compilateurs représentent généralement en interne les programmes
+comme des arbres ; les documents XML sont des arbres ; et beaucoup de conteneurs sont basés sur des
+arbres, comme les arbres bicolores.
+
+Nous allons maintenant examiner comment de tels arbres sont représentés et manipulés en Scala à travers
+d'un petit programme de calculatrice. Le but de ce programme est de manipuler des expressions arithmétiques
+simples composées de sommes, de constantes numériques et de variables. Deux exemples de telles expressions
+sont `1+2` et `(x+x)+(7+y)`.
+
+Nous devons d'abord décider d'une représentation pour de telles expressions.
+La manière la plus naturelle est un arbre où chaque nœud représente une opération (ici, une addition) et
+chaque feuille est une valeur (ici des constantes ou variables).
+
+En Java, un tel arbre serait représenté par une super classe abstraite pour les arbres et une
+sous classe concrète pour chaque nœud et feuille. Dans un langage de programmation fonctionnelle,
+on utiliserait plutôt un type de donnée algébrique pour faire la même chose. Scala fournit le concept de
+*case class* qui est quelque part entre ces deux concepts. Voici comment elles peuvent être utilisées pour
+définir le type des arbres pour notre exemple :
+
+ abstract class Arbre
+ case class Somme(l: Arbre, r: Arbre) extends Arbre
+ case class Var(n: String) extends Arbre
+ case class Const(v: Int) extends Arbre
+
+Le fait que les classes `Somme`, `Var` et `Const` sont définies en tant que case class signifie qu'elles
+différent des classes traditionnelles en différents points :
+
+- le mot clé `new` n'est pas obligatoire lors de la création d'instance de ces classes (c'est-à-dire qu'on
+ peut écrire `Const(5)` à la place de `new Const(5)`) ;
+- les fonctions accesseurs sont automatiquement définies pour les paramètres du constructeur
+ (c'est-à-dire qu'il est possible de récupérer la valeur du paramètre du constructeur `v` pour une instance `c` de
+ la classe `Const` en écrivant tout simplement `c.v`) ;
+- une définition par défaut des méthodes `equals` et `hashCode` est fournie, qui se base sur la
+ *structure* des instances et non pas leur identité ;
+- une définition par défaut de la méthode `toString` est fournie et imprime la valeur "à la source"
+ (par exemple, l'arbre pour l'expression `x+1` s'imprime comme `Somme(Var(x),Const(1))`) ;
+- les instances de ces classes peuvent être décomposées avec un *pattern matching* (filtrage par motif)
+ comme nous le verrons plus bas.
+
+Maintenant que nous avons défini le type de données pour représenter nos expressions arithmétiques,
+il est temps de définir des opérations pour les manipuler. Nous allons commencer par une fonction
+pour évaluer une expression dans un certain *environnement*. Le but de cet environnement est de
+donner des valeurs aux variables. Par exemple, l'expression `x+1` évaluée dans un environnement qui
+associe la valeur `5` à la variable `x`, écrit `{ x -> 5 }`, donne comme résultat `6`.
+
+Il faut donc trouver un moyen de représenter ces environnements. Nous pouvons certes utiliser
+une sorte de structure de données associatives comme une table de hashage, mais nous pouvons aussi
+utiliser directement des fonctions ! Un environnement n'est ni plus ni moins qu'une fonction qui associe
+une valeur à une variable. L'environnement `{ x -> 5 }` décrit plus tôt peut être écrit simplement comme
+ceci en Scala :
+
+ { case "x" => 5 }
+
+Cette notation définit une fonction qui, quand on lui donne une String `"x"` en entrée, retourne l'entier
+`5` et renvoie une exception dans les autres cas.
+
+Avant d'écrire la fonction d'évaluation, donnons un nom au type de ces environnements.
+Nous pouvons toujours utiliser le `String => Int` pour ces environnements mais cela simplifie
+le programme si nous introduisons un nom pour ce type et rendra les modifications futures plus simples.
+En Scala, on le réalise avec la notation suivante :
+
+ type Environnement = String => Int
+
+À partir de maintenant, le type `Environnement` peut être utilisé comme un alias comme
+le type des fonctions de `String` à `Int`.
+
+Maintenant, nous pouvons donner la définition de l'évaluation de fonction.
+Théoriquement, c'est très simple : la valeur d'une somme de deux expressions
+est tout simplement la somme des valeurs de ces expressions ; la valeur d'une
+variable est obtenue directement à partir de l'environnement ; la valeur d'une
+constante est la constante elle-même. Pour l'exprimer en Scala, ce n'est pas plus
+compliqué :
+
+ def eval(a: Arbre, env: Environnement): Int = a match {
+ case Somme(l, r) => eval(l, env) + eval(r, env)
+ case Var(n) => env(n)
+ case Const(v) => v
+ }
+
+Cette fonction d'évaluation fonctionne en effectuant un pattern matching
+sur l'arbre `a`. De façon intuitive, la signification de la définition ci-dessus
+devrait être claire :
+
+1. Tout d'abord, il vérifie si l'arbre `a` est une `Somme`. Si c'est le cas,
+ il relie le sous arbre de gauche à une nouvelle variable appelée `l` et
+ le sous arbre de gauche à une variable appelée `r`. Ensuite, il traite
+ l'expression à droite de la flèche : cette expression peut
+ utiliser (dans notre exemple, c'est le cas) les deux variables `l` et `r` extraites dans le
+ motif décrit à gauche de la flèche ;
+2. Si la première vérification échoue, c'est-à-dire que l'arbre n'est pas une `Somme`,
+ on continue et on vérifie si `a` est une `Var`. Si c'est le cas,
+ il relie le nom contenu dans le nœud `Var` à une variable `n` et
+ il traite l'expression à droite de la flèche ;
+3. Si la deuxième vérification échoue, c'est-à-dire que l'arbre n'est ni
+ une `Somme` ni une `Var`, on vérifie si l'arbre est un `Const`. Si
+ c'est le cas, il relie la valeur contenue dans le nœud `Const` à une
+ variable `v` et il traite l'expression à droite de la flèche ;
+4. Enfin, si toutes les vérifications échouent, une exception est levée pour signaler
+ l'échec de l'expression. Dans notre cas, cela pourrait arriver si
+ d'autres sous classes de `Arbre` étaient déclarées.
+
+Nous observons que l'idée basique du pattern matching est de faire correspondre
+une valeur à une série de motifs et dès qu'un motif correspond, extraire
+et nommer les différentes parties de la valeur pour enfin évaluer du
+code qui, généralement, utilise ces parties nommées.
+
+Un développeur orienté objet chevronné pourrait se demander pourquoi nous n'avions pas
+défini `eval` comme une *méthode* de la classe `Arbre` et de ces
+sous classes. En effet, nous aurions pu le faire, étant donné que Scala autorise
+la définition de méthodes dans les case class tout comme dans les classes normales.
+Décider d'utiliser un pattern matching ou des méthodes est donc une question de
+goût mais a aussi des implications importantes sur l'extensibilité :
+
+- quand on utilise des méthodes, il est facile d'ajouter un nouveau type de nœud en même temps
+ qu'une nouvelle sous classe de `Arbre` est définie. Par contre,
+ ajouter une nouvelle opération pour manipuler un arbre est
+ fastidieux car il demande de modifier toutes les sous classes de `Arbre` ;
+- quand on utilise un pattern matching, la situation est inversée : ajouter un
+ nouveau type de nœud demande la modification de toutes les fonctions qui effectuent
+ un pattern matching sur un arbre pour prendre en compte le nouveau nœud.
+ Par contre, ajouter une nouvelle opération est facile en la définissant
+ en tant que fonction indépendante.
+
+Pour explorer plus loin dans le pattern matching, définissons une autre opération
+sur les expressions arithmétiques : la dérivée de fonction. Le lecteur doit
+garder à l'esprit les règles suivantes par rapport à cette opération :
+
+1. la dérivée d'une somme est la somme des dérivées ;
+2. la dérivée d'une variable `v` est 1 si `v` est égale la
+ variable utilisée pour la dérivation et zéro sinon ;
+3. la dérivée d'une constante est zéro.
+
+Ces règles peuvent presque être traduites littéralement en du code Scala
+pour obtenir la définition suivante :
+
+ def derivee(a: Arbres, v: String): Arbres = a match {
+ case Somme(l, r) => Somme(derivee(l, v), derivee(r, v))
+ case Var(n) if (v == n) => Const(1)
+ case _ => Const(0)
+ }
+
+Cette fonction introduit deux nouveaux concepts reliés au pattern matching.
+
+Premièrement, l'expression `case` qui peut être utilisé avec un *garde* qui suit le mot clé `if`.
+Ce garde empêche le pattern matching de réussir à moins que l'expression soit vraie. Ici, il est utilisé
+pour s'assurer qu'on retourne la constante `1` uniquement si le nom de
+la variable se faisant dériver est la même que la variable de dérivation
+`v`. La seconde nouvelle fonctionnalité du pattern matching utilisée ici est
+le motif *joker*, représenté par `_`, qui est un motif correspondant à
+n'importe quelle valeur sans lui donner un nom.
+
+Nous n'avons pas encore exploré l'étendue du pouvoir du pattern matching, mais nous
+nous arrêterons ici afin de garder ce document court. Nous voulons toujours
+voir comment les deux fonctions ci-dessus fonctionnent dans un exemple réel. Pour se
+faire, écrivons une fonction `main` simple qui effectue plusieurs opérations sur l'expression
+`(x+x)+(7+y)` : elle évalue tout d'abord sa valeur dans l'environnement
+`{ x -> 5, y -> 7 }` puis on la dérive par rapport à `x` et par rapport à `y`.
+
+ def main(args: Array[String]): Unit = {
+ val exp: Arbre = Somme(Somme(Var("x"),Var("x")),Somme(Const(7),Var("y")))
+ val env: Environnement = { case "x" => 5 case "y" => 7 }
+ println("Expression : " + exp)
+ println("Évaluation avec x=5, y=7 : " + eval(exp, env))
+ println("Dérivée par rapport à x :\n " + derivee(exp, "x"))
+ println("Dérivée par rapport à y :\n " + derivee(exp, "y"))
+ }
+
+Vous devrez envelopper le type `Environnement` et les méthodes`eval`, `derivee` et `main`
+dans un objet `Calc` avant de compiler. En exécutant ce programme, on obtient le résultat attendu :
+
+ Expression : Somme(Somme(Var(x),Var(x)),Somme(Const(7),Var(y)))
+ Évaluation avec x=5, y=7 : 24
+ Dérivée par rapport à x :
+ Somme(Somme(Const(1),Const(1)),Somme(Const(0),Const(0)))
+ Dérivée par rapport à y :
+ Somme(Somme(Const(0),Const(0)),Somme(Const(0),Const(1)))
+
+En examinant la sortie, on voit que le résultat de la dérivée devrait être simplifiée avant
+d'être présentée à l'utilisateur. Définir une simplification basique en utilisant
+un pattern matching est un problème intéressant (mais curieusement délicat), laissé
+comme exercice pour le lecteur.
+
+## Traits
+
+Hormis le fait d'hériter du code d'une super classe, une classe Scala peut aussi
+importer du code d'un ou de plusieurs *traits*.
+
+Peut-être que le moyen le plus simple pour un développeur Java de comprendre les traits
+est de le voir comme une interface qui peut aussi contenir du code. En
+Scala, quand une classe hérite d'un trait, elle implémente son interface et
+hérite de tout le code contenu dans ce trait.
+
+Notez que depuis Java 8, les interfaces Java peut aussi contenir du code, soit
+en utilisant le mot clé `default` soit avec des méthodes statiques.
+
+Pour s'apercevoir de l'utilité des traits, regardons un exemple classique :
+les objets ordonnés. Il est souvent utile de pouvoir comparer des objets
+d'une même classe, par exemple pour les trier. En Java,
+les objets qui sont comparables implémentent l'interface `Comparable`.
+En Scala, on peut faire un peu mieux qu'en Java en définissant
+notre équivalent de `Comparable` en tant que trait, qu'on appellera
+`Ord`.
+
+Quand on compare des objets, six différents prédicats peuvent être utiles :
+plus petit, plus petit ou égal, égal, inégal, plus grand, plus grand ou égal.
+Cependant, tous les définir est fastidieux, surtout que quatre de ces six
+prédicats peuvent être exprimés en utilisant les deux restantes. En effet,
+en utilisant les prédicats égal et plus petit (par exemple), on peut
+exprimer les autres. En Scala, toutes ces observations peuvent être
+capturées dans la déclaration de trait suivante :
+
+ trait Ord {
+ def < (that: Any): Boolean
+ def <=(that: Any): Boolean = (this < that) || (this == that)
+ def > (that: Any): Boolean = !(this <= that)
+ def >=(that: Any): Boolean = !(this < that)
+ }
+
+Cette définition crée à la fois un nouveau type appelé `Ord`,
+qui joue un rôle similaire à l'interface Java `Comparable`, et
+des implémentations par défaut de trois prédicats par rapport à un
+quatrième prédicat abstrait. Les prédicats d'égalité et d'inégalité n'apparaissent pas
+ici vu qu'ils sont présents par défaut dans tous les objets.
+
+Le type `Any` qui est utilisé plus haut est le type
+qui est le super type de tous les autres types en Scala. Il peut être vu comme une
+version plus générale du type Java `Object`, puisqu'il est aussi un
+super type de types basic comme `Int`, `Float`, etc.
+
+Pour rendre les objets d'une classes comparables, il est alors suffisant de
+définir les prédicats qui testent l'égalité et l'infériorité, puis les mixer
+dans la classe `Ord` ci-dessus. Comme exemple, définissons une
+classe `Date` qui représente les dates dans le calendrier grégorien. Elles
+sont composées d'un jour, un mois et une année, que nous allons
+représenter avec des entiers. Nous commençons toutefois la définition de la
+classe `Date` comme ceci :
+
+ class Date(a: Int, m: Int, j: Int) extends Ord {
+ def annee = a
+ def mois = m
+ def jour = j
+ override def toString(): String = annee + "-" + mois + "-" + jour
+
+La partie importante ici est la déclaration `extends Ord` qui
+suit le nom de la classe et ses paramètres. Cela veut dire que la
+classe `Date` hérite du trait `Ord`.
+
+Ensuite, nous redéfinissons la méthode `equals`, héritée de `Object`,
+pour comparer correctement les dates en comparant leur
+champs individuels. L'implémentation par défaut de `equals` n'est pas
+utilisable, car en Java, elle compare les objets physiquement. On arrive
+à la définition suivante :
+
+ override def equals(that: Any): Boolean =
+ that.isInstanceOf[Date] && {
+ val d = that.asInstanceOf[Date]
+ d.jour == jour && d.mois == mois && d.annee == annee
+ }
+
+Cette méthode utilise les méthodes prédéfinies `isInstanceOf` et
+`asInstanceOf`. La première méthode, `isInstanceOf` correspond à l'opérateur
+Java `instanceof` et retourne true si et seulement si l'objet
+sur lequel elle est appliquée est une instance du type donné.
+La deuxième, `asInstanceOf`, correspond à l'opérateur de conversion de type :
+si l'objet est une instance du type donné, il est vu en tant que tel,
+sinon une `ClassCastException` est levée.
+
+Enfin, la dernière méthode à définir est le prédicat qui teste l'infériorité
+comme décrit plus loin. Elle utilise une autre méthode,
+`error` du paquet `scala.sys`, qui lève une exception avec le message d'erreur donné.
+
+ def <(that: Any): Boolean = {
+ if (!that.isInstanceOf[Date])
+ sys.error("on ne peut pas comparer " + that + " et une Date")
+
+ val d = that.asInstanceOf[Date]
+ (annee < d.annee) ||
+ (annee == d.annee && (mois < d.mois ||
+ (mois == d.mois && jour < d.jour)))
+ }
+
+Cela complète la définition de la classe `Date`. Les instances de
+cette classe peuvent être vues soit comme des dates, soit comme des objets comparables.
+De plus, elles définissent les six prédicats de comparaison mentionnés
+ci-dessus : `equals` et `<` car elles apparaissent directement dans
+la définition de la classe `Date`, ainsi que les autres qui sont directement héritées du trait `Ord`.
+
+Bien sûr, les traits sont utiles dans d'autres situations que celle décrite ici,
+mais discuter de leurs applications plus amplement est hors de la
+portée de document.
+
+## Généricité
+
+La dernière caractéristique de Scala que nous allons explorer dans ce tutoriel est
+la généricité. Les développeurs Java devraient être conscients des problèmes
+posés par le manque de généricité dans leur langage, une lacune qui
+a été compensée avec Java 1.5.
+
+La généricité est la capacité d'écrire du code paramétrisé par des types. Par
+exemple, un développeur qui écrit une librairie pour des listes liées fait face au
+problème de décider quel type donner aux éléments de la liste.
+Comme cette liste est destinée à être utilisée dans divers contextes, il n'est
+pas possible de décider quel type doit avoir les éléments de liste, par exemple,
+`Int`. Ce serait complètement arbitraire et excessivement restrictif.
+
+Les développeurs Java se retrouvent à utiliser `Object`, le super type de
+tous les objets. Cependant, cette solution est loin d'être
+idéale, puisqu'elle ne marche pas pour les types basiques (`int`,
+`long`, `float`, etc.) et cela implique que le développeur
+devra faire un certain nombre de conversions de types.
+
+Scala rend possible la définition de classes (et de méthodes) génériques pour
+résoudre ce problème. Examinons ceci au travers d'un exemple d'une
+classes conteneur la plus simple possible : une référence, qui peut être
+vide ou pointer vers un objet typé.
+
+ class Reference[T] {
+ private var contenu: T = _
+ def set(valeur: T) { contenu = valeur }
+ def get: T = contenu
+ }
+
+La classe `Reference` est paramétrisé par un type appelé `T`
+qui est le type de son élément. Ce type est utilisé dans le corps de la
+classe en tant que de la variable `contenu`, l'argument de la méthode
+`set` et le type de retour de la méthode `get`.
+
+L'échantillon de code ci-dessus introduit les variables en Scala, ce qui ne devrait pas
+demander plus d'explications. Cependant, il est intéressant de voir que
+la valeur initiale donnée à la variable est `_` qui représente
+une valeur par défaut. Cette valeur par défaut est 0 pour les types numériques,
+`false` pour le type `Boolean`, `()` pour le type `Unit`
+et `null` pour tous les types d'objet.
+
+Pour utiliser cette classe `Reference`, il faut spécifier quel type utiliser
+pour le type paramètre `T`, le type de l'élément contenu dans la cellule.
+Par exemple, pour créer et utiliser une cellule contenant
+un entier, on peut écrire :
+
+ object ReferenceEntier {
+ def main(args: Array[String]): Unit = {
+ val cellule = new Reference[Int]
+ cellule.set(13)
+ println("La référence contient la moitié de " + (cellule.get * 2))
+ }
+ }
+
+Comme on peut le voir dans l'exemple, il n'est pas nécessaire de convertir la valeur
+retournée par la méthode `get` avant de pouvoir l'utiliser en tant qu'entier. Il
+n'est pas possible de stocker autre chose d'un entier dans cette
+cellule particulière, puisqu'elle a été déclarée comme portant un entier.
+
+## Conclusion
+
+Ce document donne un rapide aperçu du langage Scala et
+présente quelques exemples basiques. Le développeur intéressé peut poursuivre sa lecture,
+par exemple, en lisant le *[Tour of Scala](https://docs.scala-lang.org/tour/tour-of-scala.html)*
+(document en anglais) et consulter la *spécification du langage Scala* si nécessaire.
diff --git a/glossary/index.md b/_glossary/index.md
similarity index 86%
rename from glossary/index.md
rename to _glossary/index.md
index 6959c4048a..9d4d490c65 100644
--- a/glossary/index.md
+++ b/_glossary/index.md
@@ -1,393 +1,395 @@
---
layout: glossary
title: Glossary
+
+languages: [zh-cn]
---
-
-* #### algebraic data type
+* ### algebraic data type
A type defined by providing several alternatives, each of which comes with its own constructor. It usually comes with a way to decompose the type through pattern matching. The concept is found in specification languages and functional programming languages. Algebraic data types can be emulated in Scala with case classes.
-* #### alternative
+* ### alternative
A branch of a match expression. It has the form “`case` _pattern_ => _expression_.” Another name for alternative is _case_.
-* #### annotation
+* ### annotation
An annotation appears in source code and is attached to some part of the syntax. Annotations are computer processable, so you can use them to effectively add an extension to Scala.
-* #### anonymous class
+* ### anonymous class
An anonymous class is a synthetic subclass generated by the Scala compiler from a new expression in which the class or trait name is followed by curly braces. The curly braces contains the body of the anonymous subclass, which may be empty. However, if the name following new refers to a trait or class that contains abstract members, these must be made concrete inside the curly braces that define the body of the anonymous subclass.
-* #### anonymous function
+* ### anonymous function
Another name for [function literal](#function-literal).
-* #### apply
+* ### apply
You can apply a method, function, or closure to arguments, which means you invoke it on those arguments.
-* #### argument
+* ### argument
When a function is invoked, an argument is passed for each parameter of that function. The parameter is the variable that refers to the argument. The argument is the object passed at invocation time. In addition, applications can take (command line) arguments that show up in the `Array[String]` passed to main methods of singleton objects.
-* #### assign
+* ### assign
You can assign an object to a variable. Afterwards, the variable will refer to the object.
-* #### auxiliary constructor
+* ### auxiliary constructor
Extra constructors defined inside the curly braces of the class definition, which look like method definitions named `this`, but with no result type.
-* #### block
-One or more expressions and declarations surrounded by curly braces. When the block evaluates, all of its expressions and declarations are processed in order, and then the block returns the value of the last expression as its own value. Blocks are commonly used as the bodies of functions, [for expressions](#for-expression), `while` loops, and any other place where you want to group a number of statements together. More formally, a block is an encapsulation construct for which you can only see side effects and a result value. The curly braces in which you define a class or object do not, therefore, form a block, because fields and methods (which are defined inside those curly braces) are visible from the out- side. Such curly braces form a template.
+* ### block
+One or more expressions and declarations surrounded by curly braces. When the block evaluates, all of its expressions and declarations are processed in order, and then the block returns the value of the last expression as its own value. Blocks are commonly used as the bodies of functions, [for expressions](#for-expression), `while` loops, and any other place where you want to group a number of statements together. More formally, a block is an encapsulation construct for which you can only see side effects and a result value. The curly braces in which you define a class or object do not, therefore, form a block, because fields and methods (which are defined inside those curly braces) are visible from the outside. Such curly braces form a template.
-* #### bound variable
+* ### bound variable
A bound variable of an expression is a variable that’s both used and defined inside the expression. For instance, in the function literal expression `(x: Int) => (x, y)`, both variables `x` and `y` are used, but only `x` is bound, because it is defined in the expression as an `Int` and the sole argument to the function described by the expression.
-* #### by-name parameter
+* ### by-name parameter
A parameter that is marked with a `=>` in front of the parameter type, e.g., `(x: => Int)`. The argument corresponding to a by-name parameter is evaluated not before the method is invoked, but each time the parameter is referenced by name inside the method. If a parameter is not by-name, it is by-value.
-* #### by-value parameter
+* ### by-value parameter
A parameter that is not marked with a `=>` in front of the parameter type, e.g., `(x: Int)`. The argument corresponding to a by-value parameter is evaluated before the method is invoked. By-value parameters contrast with by-name parameters.
-* #### class
+* ### class
Defined with the `class` keyword, a _class_ may either be abstract or concrete, and may be parameterized with types and values when instantiated. In `new Array[String](2)`, the class being instantiated is `Array` and the type of the value that results is `Array[String]`. A class that takes type parameters is called a _type constructor_. A type can be said to have a class as well, as in: the class of type `Array[String]` is `Array`.
-* #### closure
+* ### closure
A function object that captures free variables, and is said to be “closed” over the variables visible at the time it is created.
-* #### companion class
+* ### companion class
A class that shares the same name with a singleton object defined in the same source file. The class is the singleton object’s companion class.
-* #### companion object
+* ### companion object
A singleton object that shares the same name with a class defined in the same source file. Companion objects and classes have access to each other’s private members. In addition, any implicit conversions defined in the companion object will be in scope anywhere the class is used.
-* #### contravariant
+* ### contravariant
A _contravariant_ annotation can be applied to a type parameter of a class or trait by putting a minus sign (-) before the type parameter. The class or trait then subtypes contravariantly with—in the opposite direction as—the type annotated parameter. For example, `Function1` is contravariant in its first type parameter, and so `Function1[Any, Any]` is a subtype of `Function1[String, Any]`.
-* #### covariant
+* ### covariant
A _covariant_ annotation can be applied to a type parameter of a class or trait by putting a plus sign (+) before the type parameter. The class or trait then subtypes covariantly with—in the same direction as—the type annotated parameter. For example, `List` is covariant in its type parameter, so `List[String]` is a subtype of `List[Any]`.
-* #### currying
+* ### currying
A way to write functions with multiple parameter lists. For instance `def f(x: Int)(y: Int)` is a curried function with two parameter lists. A curried function is applied by passing several arguments lists, as in: `f(3)(4)`. However, it is also possible to write a _partial application_ of a curried function, such as `f(3)`.
-* #### declare
+* ### declare
You can _declare_ an abstract field, method, or type, which gives an entity a name but not an implementation. The key difference between declarations and definitions is that definitions establish an implementation for the named entity, declarations do not.
-* #### define
+* ### define
To _define_ something in a Scala program is to give it a name and an implementation. You can define classes, traits, singleton objects, fields, methods, local functions, local variables, _etc_. Because definitions always involve some kind of implementation, abstract members are declared not defined.
-* #### direct subclass
+* ### direct subclass
A class is a _direct subclass_ of its direct superclass.
-* #### direct superclass
+* ### direct superclass
The class from which a class or trait is immediately derived, the nearest class above it in its inheritance hierarchy. If a class `Parent` is mentioned in a class `Child`’s optional extends clause, then `Parent` is the direct superclass of `Child`. If a trait is mentioned in `Child`’s extends clause, the trait’s direct superclass is the `Child`’s direct superclass. If `Child` has no extends clause, then `AnyRef` is the direct superclass of `Child`. If a class’s direct superclass takes type parameters, for example class `Child` extends `Parent[String]`, the direct superclass of `Child` is still `Parent`, not `Parent[String]`. On the other hand, `Parent[String]` would be the direct supertype of `Child`. See [supertype](#supertype) for more discussion of the distinction between class and type.
-* #### equality
+* ### equality
When used without qualification, _equality_ is the relation between values expressed by `==`. See also [reference equality](#reference-equality).
-* #### existential type
+* ### existential type
An existential type includes references to type variables that are unknown. For example, `Array[T] forSome { type T }` is an existential type. It is an array of `T`, where `T` is some completely unknown type. All that is assumed about `T` is that it exists at all. This assumption is weak, but it means at least that an `Array[T] forSome { type T }` is indeed an array and not a banana.
-* #### expression
+* ### expression
Any bit of Scala code that yields a result. You can also say that an expression _evaluates_ to a result or _results_ in a value.
-* #### filter
+* ### filter
An `if` followed by a boolean expression in a [for expression](#for-expression). In `for(i <- 1 to 10; if i % 2 == 0)`, the filter is “`if i % 2 == 0`”. The value to the right of the `if` is the [filter expression](#filter-expression). Also known as a guard.
-* #### filter expression
+* ### filter expression
A _filter expression_ is the boolean expression following an `if` in a [for expression](#for-expression). In `for( i <- 1 to 10 ; if i % 2 == 0)`,the filter expression is “`i % 2 == 0`”.
-* #### first-class function
+* ### first-class function
Scala supports _first-class functions_, which means you can express functions in function literal syntax, i.e., `(x: Int) => x + 1`, and that functions can be represented by objects, which are called [function values](#function-value).
-* #### for comprehension
+* ### for comprehension
A _for comprehension_ is a type of [for expression](#for-expression) that creates a new collection. For each iteration of the `for` comprehension, the [yield](#yield) clause defines an element of the new collection. For example, `for (i <- (0 until 2); j <- (2 until 4)) yield (i, j)` returns the collection `Vector((0,2), (0,3), (1,2), (1,3))`.
-* #### for expression
+* ### for expression
A _for expression_ is either a [for loop](#for-loop), which iterates over one or more collections, or a [for comprehension](#for-comprehension), which builds a new collection from the elements of one or more collections. A `for` expression is built up of [generators](#generator), [filters](#filter), variable definitions, and (in the case of [for comprehensions](#for-comprehension)) a [yield](#yield) clause.
-* #### for loop
+* ### for loop
A _for loop_ is a type of [for expression](#for-expression) that loops over one or more collections. Since `for` loops return unit, they usually produce side-effects. For example, `for (i <- 0 until 100) println(i)` prints the numbers 0 through 99.
-* #### free variable
+* ### free variable
A _free variable_ of an expression is a variable that’s used inside the expression but not defined inside the expression. For instance, in the function literal expression `(x: Int) => (x, y)`, both variables `x` and `y` are used, but only `y` is a free variable, because it is not defined inside the expression.
-* #### function
+* ### function
A _function_ can be [invoked](#invoke) with a list of arguments to produce a result. A function has a parameter list, a body, and a result type. Functions that are members of a class, trait, or singleton object are called [methods](#method). Functions defined inside other functions are called [local functions](#local-function). Functions with the result type of `Unit` are called [procedures](#procedure). Anonymous functions in source code are called [function literals](#function-literal). At run time, function literals are instantiated into objects called [function values](#function-value).
-* #### function literal
-A function with no name in Scala source code, specified with function literal syntax. For example, `(x: Int, y: Int) => x + y`.
+* ### function literal
+A function with no name in Scala source code, specified with _function literal_ syntax. For example, `(x: Int, y: Int) => x + y`.
-* #### function value
-A function object that can be invoked just like any other function. A function value’s class extends one of the `FunctionN` traits (e.g., `Function0`, `Function1`) from package `scala`, and is usually expressed in source code via [function literal](#function-literal) syntax. A function value is “invoked” when its apply method is called. A function value that captures free variables is a [closure](#closure).
+* ### function value
+A function object that can be invoked just like any other function. A _function value_’s class extends one of the `FunctionN` traits (e.g., `Function0`, `Function1`) from package `scala`, and is usually expressed in source code via [function literal](#function-literal) syntax. A function value is “invoked” when its apply method is called. A function value that captures free variables is a [closure](#closure).
-* #### functional style
+* ### functional style
The _functional style_ of programming emphasizes functions and evaluation results and deemphasizes the order in which operations occur. The style is characterized by passing function values into looping methods, immutable data, methods with no side effects. It is the dominant paradigm of languages such as Haskell and Erlang, and contrasts with the [imperative style](#imperative-style).
-* #### generator
-A generator defines a named val and assigns to it a series of values in a [for expression](#for-expression). For example, in `for(i <- 1 to 10)`, the generator is “`i <- 1 to 10`”. The value to the right of the `<-` is the [generator expression](#generator-expression).
+* ### generator
+A _generator_ defines a named val and assigns to it a series of values in a [for expression](#for-expression). For example, in `for(i <- 1 to 10)`, the generator is “`i <- 1 to 10`”. The value to the right of the `<-` is the [generator expression](#generator-expression).
-* #### generator expression
-A generator expression generates a series of values in a [for expression](#for-expression). For example, in `for(i <- 1 to 10)`, the generator expression is “`1 to 10`”.
+* ### generator expression
+A _generator expression_ generates a series of values in a [for expression](#for-expression). For example, in `for(i <- 1 to 10)`, the generator expression is “`1 to 10`”.
-* #### generic class
-A class that takes type parameters. For example, because `scala.List` takes a type parameter, `scala.List` is a generic class.
+* ### generic class
+A class that takes type parameters. For example, because `scala.List` takes a type parameter, `scala.List` is a _generic class_.
-* #### generic trait
-A trait that takes type parameters. For example, because trait `scala.collection.Set` takes a type parameter, it is a generic trait.
+* ### generic trait
+A trait that takes type parameters. For example, because trait `scala.collection.Set` takes a type parameter, it is a _generic trait_.
-* #### guard
+* ### guard
See [filter](#filter).
-* #### helper function
+* ### helper function
A function whose purpose is to provide a service to one or more other functions nearby. Helper functions are often implemented as local functions.
-* #### helper method
+* ### helper method
A [helper function](#helper-function) that’s a member of a class. Helper methods are often private.
-* #### immutable
+* ### immutable
An object is _immutable_ if its value cannot be changed after it is created in any way visible to clients. Objects may or may not be immutable.
-* #### imperative style
+* ### imperative style
The _imperative style_ of programming emphasizes careful sequencing of operations so that their effects happen in the right order. The style is characterized by iteration with loops, mutating data in place, and methods with side effects. It is the dominant paradigm of languages such as C, C++, C# and Java, and contrasts with the [functional style](#functional-style).
-* #### initialize
-When a variable is defined in Scala source code, you must initialize it with an object.
+* ### initialize
+When a variable is defined in Scala source code, you must _initialize_ it with an object.
-* #### instance
+* ### instance
An _instance_, or class instance, is an object, a concept that exists only at run time.
-* #### instantiate
+* ### instantiate
To _instantiate_ a class is to make a new object from the class, an action that happens only at run time.
-* #### invariant
+* ### invariant
_Invariant_ is used in two ways. It can mean a property that always holds true when a data structure is well-formed. For example, it is an invariant of a sorted binary tree that each node is ordered before its right subnode, if it has a right subnode. Invariant is also sometimes used as a synonym for nonvariant: “class `Array` is invariant in its type parameter.”
-* #### invoke
+* ### invoke
You can _invoke_ a method, function, or closure _on_ arguments, meaning its body will be executed with the specified arguments.
-* #### JVM
+* ### JVM
The _JVM_ is the Java Virtual Machine, or [runtime](#runtime), that hosts a running Scala program.
-* #### literal
+* ### literal
`1`, `"One"`, and `(x: Int) => x + 1` are examples of _literals_. A literal is a shorthand way to describe an object, where the shorthand exactly mirrors the structure of the created object.
-* #### local function
+* ### local function
A _local function_ is a `def` defined inside a block. To contrast, a `def` defined as a member of a class, trait, or singleton object is called a [method](#method).
-* #### local variable
+* ### local variable
A _local variable_ is a `val` or `var` defined inside a block. Although similar to [local variables](#local-variable), parameters to functions are not referred to as local variables, but simply as parameters or “variables” without the “local.”
-* #### member
+* ### member
A _member_ is any named element of the template of a class, trait, or singleton object. A member may be accessed with the name of its owner, a dot, and its simple name. For example, top-level fields and methods defined in a class are members of that class. A trait defined inside a class is a member of its enclosing class. A type defined with the type keyword in a class is a member of that class. A class is a member of the package in which is it defined. By contrast, a local variable or local function is not a member of its surrounding block.
-* #### message
+* ### message
Actors communicate with each other by sending each other _messages_. Sending a message does not interrupt what the receiver is doing. The receiver can wait until it has finished its current activity and its invariants have been reestablished.
-* #### meta-programming
+* ### meta-programming
Meta-programming software is software whose input is itself software. Compilers are meta-programs, as are tools like `scaladoc`. Meta-programming software is required in order to do anything with an annotation.
-* #### method
+* ### method
A _method_ is a function that is a member of some class, trait, or singleton object.
-* #### mixin
-_Mixin_ is what a trait is called when it is being used in a mixin composition. In other words, in “`trait Hat`,” `Hat` is just a trait, but in “`new Cat extends AnyRef with Hat`,” `Hat` can be called a mixin. When used as a verb, “mix in” is two words. For example, you can _mix_ traits _in_to classes or other traits.
+* ### mixin
+_Mixin_ is what a trait is called when it is being used in a mixin composition. In other words, in “`trait Hat`,” `Hat` is just a trait, but in “`new Cat extends AnyRef with Hat`,” `Hat` can be called a mixin. When used as a verb, “mix in” is two words. For example, you can _mix_ traits _in_ to classes or other traits.
-* #### mixin composition
+* ### mixin composition
The process of mixing traits into classes or other traits. _Mixin composition_ differs from traditional multiple inheritance in that the type of the super reference is not known at the point the trait is defined, but rather is determined anew each time the trait is mixed into a class or other trait.
-* #### modifier
+* ### modifier
A keyword that qualifies a class, trait, field, or method definition in some way. For example, the `private` modifier indicates that a class, trait, field, or method being defined is private.
-* #### multiple definitions
+* ### multiple definitions
The same expression can be assigned in _multiple definitions_ if you use the syntax `val v1, v2, v3 = exp`.
-* #### nonvariant
+* ### nonvariant
A type parameter of a class or trait is by default _nonvariant_. The class or trait then does not subtype when that parameter changes. For example, because class `Array` is nonvariant in its type parameter, `Array[String]` is neither a subtype nor a supertype of `Array[Any]`.
-* #### operation
+* ### operation
In Scala, every _operation_ is a method call. Methods may be invoked in _operator notation_, such as `b + 2`, and when in that notation, `+` is an _operator_.
-* #### parameter
+* ### parameter
Functions may take zero to many _parameters_. Each parameter has a name and a type. The distinction between parameters and arguments is that arguments refer to the actual objects passed when a function is invoked. Parameters are the variables that refer to those passed arguments.
-* #### parameterless function
-A function that takes no parameters, which is de- fined without any empty parentheses. Invocations of parameterless functions may not supply parentheses. This supports the [uniform access principle](#uniform-access-principle), which enables the `def` to be changed into a `val` without requiring a change to client code.
+* ### parameterless function
+A function that takes no parameters, which is defined without any empty parentheses. Invocations of parameterless functions may not supply parentheses. This supports the [uniform access principle](#uniform-access-principle), which enables the `def` to be changed into a `val` without requiring a change to client code.
-* #### parameterless method
+* ### parameterless method
A _parameterless method_ is a parameterless function that is a member of a class, trait, or singleton object.
-* #### parametric field
+* ### parametric field
A field defined as a class parameter.
-* #### partially applied function
+* ### partially applied function
A function that’s used in an expression and that misses some of its arguments. For instance, if function `f` has type `Int => Int => Int`, then `f` and `f(1)` are _partially applied functions_.
-* #### path-dependent type
+* ### path-dependent type
A type like `swiss.cow.Food`. The `swiss.cow` part is a path that forms a reference to an object. The meaning of the type is sensitive to the path you use to access it. The types `swiss.cow.Food` and `fish.Food`, for example, are different types.
-* #### pattern
+* ### pattern
In a `match` expression alternative, a _pattern_ follows each `case` keyword and precedes either a _pattern guard_ or the `=>` symbol.
-* #### pattern guard
+* ### pattern guard
In a `match` expression alternative, a _pattern guard_ can follow a [pattern](#pattern). For example, in “`case x if x % 2 == 0 => x + 1`”, the pattern guard is “`if x % 2 == 0`”. A case with a pattern guard will only be selected if the pattern matches and the pattern guard yields true.
-* #### predicate
+* ### predicate
A _predicate_ is a function with a `Boolean` result type.
-* #### primary constructor
+* ### primary constructor
The main constructor of a class, which invokes a superclass constructor, if necessary, initializes fields to passed values, and executes any top-level code defined between the curly braces of the class. Fields are initialized only for value parameters not passed to the superclass constructor, except for any that are not used in the body of the class and can therefore be optimized away.
-* #### procedure
+* ### procedure
A _procedure_ is a function with result type of `Unit`, which is therefore executed solely for its side effects.
-* #### reassignable
+* ### reassignable
A variable may or may not be _reassignable_. A `var` is reassignable while a `val` is not.
-* #### recursive
+* ### recursive
A function is _recursive_ if it calls itself. If the only place the function calls itself is the last expression of the function, then the function is [tail recursive](#tail-recursive).
-* #### reference
+* ### reference
A _reference_ is the Java abstraction of a pointer, which uniquely identifies an object that resides on the JVM’s heap. Reference type variables hold references to objects, because reference types (instances of `AnyRef`) are implemented as Java objects that reside on the JVM’s heap. Value type variables, by contrast, may sometimes hold a reference (to a boxed wrapper type) and sometimes not (when the object is being represented as a primitive value). Speaking generally, a Scala variable [refers](#refers) to an object. The term “refers” is more abstract than “holds a reference.” If a variable of type `scala.Int` is currently represented as a primitive Java `int` value, then that variable still refers to the `Int` object, but no reference is involved.
-* #### reference equality
+* ### reference equality
_Reference equality_ means that two references identify the very same Java object. Reference equality can be determined, for reference types only, by calling `eq` in `AnyRef`. (In Java programs, reference equality can be determined using `==` on Java [reference types](#reference-type).)
-* #### reference type
+* ### reference type
A _reference type_ is a subclass of `AnyRef`. Instances of reference types always reside on the JVM’s heap at run time.
-* #### referential transparency
+* ### referential transparency
A property of functions that are independent of temporal context and have no side effects. For a particular input, an invocation of a referentially transparent function can be replaced by its result without changing the program semantics.
-* #### refers
+* ### refers
A variable in a running Scala program always _refers_ to some object. Even if that variable is assigned to `null`, it conceptually refers to the `Null` object. At runtime, an object may be implemented by a Java object or a value of a primitive type, but Scala allows programmers to think at a higher level of abstraction about their code as they imagine it running. See also [reference](#reference).
-* #### refinement type
-A type formed by supplying a base type a number of members inside curly braces. The members in the curly braces refine the types that are present in the base type. For example, the type of “animal that eats grass” is `Animal { type SuitableFood = Grass }`.
+* ### refinement type
+A type formed by supplying a base type with a number of members inside curly braces. The members in the curly braces refine the types that are present in the base type. For example, the type of “animal that eats grass” is `Animal { type SuitableFood = Grass }`.
-* #### result
+* ### result
An expression in a Scala program yields a _result_. The result of every expression in Scala is an object.
-* #### result type
+* ### result type
A method’s _result type_ is the type of the value that results from calling the method. (In Java, this concept is called the return type.)
-* #### return
-A function in a Scala program `returns` a value. You can call this value the [result](#result) of the function. You can also say the function _results in_ the value. The result of every function in Scala is an object.
+* ### return
+A function in a Scala program _returns_ a value. You can call this value the [result](#result) of the function. You can also say the function _results in_ the value. The result of every function in Scala is an object.
-* #### runtime
+* ### runtime
The Java Virtual Machine, or [JVM](#jvm), that hosts a running Scala program. Runtime encompasses both the virtual machine, as defined by the Java Virtual Machine Specification, and the runtime libraries of the Java API and the standard Scala API. The phrase at run time (with a space between run and time) means when the program is running, and contrasts with compile time.
-* #### runtime type
+* ### runtime type
The type of an object at run time. To contrast, a [static type](#static-type) is the type of an expression at compile time. Most runtime types are simply bare classes with no type parameters. For example, the runtime type of `"Hi"` is `String`, and the runtime type of `(x: Int) => x + 1` is `Function1`. Runtime types can be tested with `isInstanceOf`.
-* #### script
+* ### script
A file containing top level definitions and statements, which can be run directly with `scala` without explicitly compiling. A script must end in an expression, not a definition.
-* #### selector
+* ### selector
The value being matched on in a `match` expression. For example, in “`s match { case _ => }`”, the selector is `s`.
-* #### self type
-A _self type_ of a trait is the assumed type of `this`, the receiver, to be used within the trait. Any concrete class that mixes in the trait must ensure that its type conforms to the trait’s self type. The most common use of self types is for dividing a large class into several traits (as described in Chapter 29 of [Programming in Scala](http://www.artima.com/shop/programming_in_scala).
+* ### self type
+A _self type_ of a trait is the assumed type of `this`, the receiver, to be used within the trait. Any concrete class that mixes in the trait must ensure that its type conforms to the trait’s self type. The most common use of self types is for dividing a large class into several traits (as described in Chapter 29 of [Programming in Scala](https://www.artima.com/shop/programming_in_scala)).
-* #### semi-structured data
+* ### semi-structured data
XML data is semi-structured. It is more structured than a flat binary file or text file, but it does not have the full structure of a programming language’s data structures.
-* #### serialization
-You can _serialize_ an object into a byte stream which can then be saved to files or transmitted over the network. You can later _deserialize_ the byte stream, even on different computer, and obtain an object that is the same as the original serialized object.
+* ### serialization
+You can _serialize_ an object into a byte stream which can then be saved to a file or transmitted over the network. You can later _deserialize_ the byte stream, even on different computer, and obtain an object that is the same as the original serialized object.
-* #### shadow
+* ### shadow
A new declaration of a local variable _shadows_ one of the same name in an enclosing scope.
-* #### signature
+* ### signature
_Signature_ is short for [type signature](#type-signature).
-* #### singleton object
+* ### singleton object
An object defined with the object keyword. Each singleton object has one and only one instance. A singleton object that shares its name with a class, and is defined in the same source file as that class, is that class’s [companion object](#companion-object). The class is its [companion class](#companion-class). A singleton object that doesn’t have a companion class is a [standalone object](#standalone-object).
-* #### standalone object
+* ### standalone object
A [singleton object](#singleton-object) that has no [companion class](#companion-class).
-* #### statement
+* ### statement
An expression, definition, or import, _i.e._, things that can go into a template or a block in Scala source code.
-* #### static type
+* ### static type
See [type](#type).
-* #### structural type
+* ### structural type
A [refinement type](#refinement-type) where the refinements are for members not in the base type. For example, `{ def close(): Unit }` is a structural type, because the base type is `AnyRef`, and `AnyRef` does not have a member named `close`.
-* #### subclass
+* ### subclass
A class is a _subclass_ of all of its [superclasses](#superclass) and [supertraits](#supertrait).
-* #### subtrait
+* ### subtrait
A trait is a _subtrait_ of all of its [supertraits](#supertrait).
-* #### subtype
+* ### subtype
The Scala compiler will allow any of a type’s _subtypes_ to be used as a substitute wherever that type is required. For classes and traits that take no type parameters, the subtype relationship mirrors the subclass relationship. For example, if class `Cat` is a subclass of abstract class `Animal`, and neither takes type parameters, type `Cat` is a subtype of type `Animal`. Likewise, if trait `Apple` is a subtrait of trait `Fruit`, and neither takes type parameters, type `Apple` is a subtype of type `Fruit`. For classes and traits that take type parameters, however, variance comes into play. For example, because abstract class `List` is declared to be covariant in its lone type parameter (i.e., `List` is declared `List[+A]`), `List[Cat]` is a subtype of `List[Animal]`, and `List[Apple]` a subtype of `List[Fruit]`. These subtype relationships exist even though the class of each of these types is `List`. By contrast, because `Set` is not declared to be covariant in its type parameter (i.e., `Set` is declared `Set[A]` with no plus sign), `Set[Cat]` is not a subtype of `Set[Animal]`. A subtype should correctly implement the contracts of its supertypes, so that the Liskov Substitution Principle applies, but the compiler only verifies this property at the level of type checking.
-* #### superclass
+* ### superclass
A class’s _superclasses_ include its direct superclass, its direct superclass’s direct superclass, and so on, all the way up to `Any`.
-* #### supertrait
+* ### supertrait
A class’s or trait’s _supertraits_, if any, include all traits directly mixed into the class or trait or any of its superclasses, plus any supertraits of those traits.
-* #### supertype
+* ### supertype
A type is a _supertype_ of all of its subtypes.
-* #### synthetic class
+* ### synthetic class
A synthetic class is generated automatically by the compiler rather than being written by hand by the programmer.
-* #### tail recursive
+* ### tail recursive
A function is _tail recursive_ if the only place the function calls itself is the last operation of the function.
-* #### target typing
+* ### target typing
_Target typing_ is a form of type inference that takes into account the type that’s expected. In `nums.filter((x) => x > 0)`, for example, the Scala compiler infers type of `x` to be the element type of `nums`, because the `filter` method invokes the function on each element of `nums`.
-* #### template
+* ### template
A _template_ is the body of a class, trait, or singleton object definition. It defines the type signature, behavior and initial state of the class, trait, or object.
-* #### trait
+* ### trait
A _trait_, which is defined with the `trait` keyword, is like an abstract class that cannot take any value parameters and can be “mixed into” classes or other traits via the process known as [mixin composition](#mixin-composition). When a trait is being mixed into a class or trait, it is called a [mixin](#mixin). A trait may be parameterized with one or more types. When parameterized with types, the trait constructs a type. For example, `Set` is a trait that takes a single type parameter, whereas `Set[Int]` is a type. Also, `Set` is said to be “the trait of” type `Set[Int]`.
-* #### type
+* ### type
Every variable and expression in a Scala program has a _type_ that is known at compile time. A type restricts the possible values to which a variable can refer, or an expression can produce, at run time. A variable or expression’s type can also be referred to as a _static type_ if necessary to differentiate it from an object’s [runtime type](#runtime-type). In other words, “type” by itself means static type. Type is distinct from class because a class that takes type parameters can construct many types. For example, `List` is a class, but not a type. `List[T]` is a type with a free type parameter. `List[Int]` and `List[String]` are also types (called ground types because they have no free type parameters). A type can have a “[class](#class)” or “[trait](#trait).” For example, the class of type `List[Int]` is `List`. The trait of type `Set[String]` is `Set`.
-* #### type constraint
+* ### type constraint
Some [annotations](#annotation) are _type constraints_, meaning that they add additional limits, or constraints, on what values the type includes. For example, `@positive` could be a type constraint on the type `Int`, limiting the type of 32-bit integers down to those that are positive. Type constraints are not checked by the standard Scala compiler, but must instead be checked by an extra tool or by a compiler plugin.
-* #### type constructor
+* ### type constructor
A class or trait that takes type parameters.
-* #### type parameter
+* ### type parameter
A parameter to a generic class or generic method that must be filled in by a type. For example, class `List` is defined as “`class List[T] { . . . `”, and method `identity`, a member of object `Predef`, is defined as “`def identity[T](x:T) = x`”. The `T` in both cases is a type parameter.
-* #### type signature
+* ### type signature
A method’s _type signature_ comprises its name, the number, order, and types of its parameters, if any, and its result type. The type signature of a class, trait, or singleton object comprises its name, the type signatures of all of its members and constructors, and its declared inheritance and mixin relations.
-* #### uniform access principle
+* ### uniform access principle
The _uniform access principle_ states that variables and parameterless functions should be accessed using the same syntax. Scala supports this principle by not allowing parentheses to be placed at call sites of parameterless functions. As a result, a parameterless function definition can be changed to a `val`, or _vice versa_, without affecting client code.
-* #### unreachable
-At the Scala level, objects can become _unreachable_, at which point the memory they occupy may be reclaimed by the runtime. Unreachable does not necessarily mean unreferenced. Reference types (instances of `AnyRef`) are implemented as objects that reside on the JVM’s heap. When an instance of a reference type becomes unreachable, it indeed becomes unreferenced, and is available for garbage collection. Value types (instances of `AnyVal`) are implemented as both primitive type values and as instances of Java wrapper types (such as `java.lang.Integer`), which reside on the heap. Value type instances can be boxed (converted from a primitive value to a wrapper object) and unboxed (converted from a wrapper object to a primitive value) throughout the lifetime of the variables that refer to them. If a value type instance currently represented as a wrapper object on the JVM’s heap becomes unreachable, it indeed becomes unreferenced, and is available for garbage collection. But if a value type currently represented as a primitive value becomes unreachable, then it does not become unreferenced, because it does not exist as an object on the JVM’s heap at that point in time. The runtime may reclaim memory occupied by unreachable objects, but if an Int, for example, is implemented at run time by a primitive Java int that occupies some memory in the stack frame of an executing method, then the memory for that object is “reclaimed” when the stack frame is popped as the method completes. Memory for reference types, such as `Strings`, may be reclaimed by the JVM’s garbage collector after they become unreachable.
+* ### unreachable
+At the Scala level, objects can become _unreachable_, at which point the memory they occupy may be reclaimed by the runtime. Unreachable does not necessarily mean unreferenced. Reference types (instances of `AnyRef`) are implemented as objects that reside on the JVM’s heap. When an instance of a reference type becomes unreachable, it indeed becomes unreferenced, and is available for garbage collection. Value types (instances of `AnyVal`) are implemented as both primitive type values and as instances of Java wrapper types (such as `java.lang.Integer`), which reside on the heap. Value type instances can be boxed (converted from a primitive value to a wrapper object) and unboxed (converted from a wrapper object to a primitive value) throughout the lifetime of the variables that refer to them. If a value type instance currently represented as a wrapper object on the JVM’s heap becomes unreachable, it indeed becomes unreferenced, and is available for garbage collection. But if a value type currently represented as a primitive value becomes unreachable, then it does not become unreferenced, because it does not exist as an object on the JVM’s heap at that point of time. The runtime may reclaim memory occupied by unreachable objects, but if an Int, for example, is implemented at run time by a primitive Java int that occupies some memory in the stack frame of an executing method, then the memory for that object is “reclaimed” when the stack frame is popped as the method completes. Memory for reference types, such as `Strings`, may be reclaimed by the JVM’s garbage collector after they become unreachable.
-* #### unreferenced
+* ### unreferenced
See [unreachable](#unreachable).
-* #### value
+* ### value
The result of any computation or expression in Scala is a _value_, and in Scala, every value is an object. The term value essentially means the image of an object in memory (on the JVM’s heap or stack).
-* #### value type
-A _value type_ is any subclass of `AnyVal`, such as `Int`, `Double`, or `Unit`. This term has meaning at the level of Scala source code. At runtime, instances of value types that correspond to Java primitive types may be implemented in terms of primitive type values or instances of wrapper types, such as `java.lang.Integer`. Over the lifetime of a value type instance, the runtime may transform it back and forth be- tween primitive and wrapper types (_i.e._, to box and unbox it).
+* ### value type
+A _value type_ is any subclass of `AnyVal`, such as `Int`, `Double`, or `Unit`. This term has meaning at the level of Scala source code. At runtime, instances of value types that correspond to Java primitive types may be implemented in terms of primitive type values or instances of wrapper types, such as `java.lang.Integer`. Over the lifetime of a value type instance, the runtime may transform it back and forth between primitive and wrapper types (_i.e._, to box and unbox it).
-* #### variable
+* ### variable
A named entity that refers to an object. A variable is either a `val` or a `var`. Both `val`s and `var`s must be initialized when defined, but only `var`s can be later reassigned to refer to a different object.
-* #### variance
+* ### variance
A type parameter of a class or trait can be marked with a _variance_ annotation, either [covariant](#covariant) (+) or [contravariant](#contravariant) (-). Such variance annotations indicate how subtyping works for a generic class or trait. For example, the generic class `List` is covariant in its type parameter, and thus `List[String]` is a subtype of `List[Any]`. By default, _i.e._, absent a `+` or `-` annotation, type parameters are [nonvariant](#nonvariant).
-* #### yield
+* ### yield
An expression can _yield_ a result. The `yield` keyword designates the result of a [for comprehension](#for-comprehension).
diff --git a/_includes/_markdown/_ru/install-cask.md b/_includes/_markdown/_ru/install-cask.md
new file mode 100644
index 0000000000..1cac104c20
--- /dev/null
+++ b/_includes/_markdown/_ru/install-cask.md
@@ -0,0 +1,45 @@
+{% altDetails require-info-box 'Установка Cask' %}
+
+{% tabs cask-install class=tabs-build-tool %}
+
+{% tab 'Scala CLI' %}
+
+Вы можете объявить зависимость от Cask с помощью следующей директивы `using`:
+
+```scala
+//> using dep com.lihaoyi::cask::0.10.2
+```
+
+{% endtab %}
+
+{% tab 'sbt' %}
+
+В файле `build.sbt` вы можете добавить зависимость от Cask:
+
+```scala
+lazy val example = project.in(file("example"))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "com.lihaoyi" %% "cask" % "0.10.2",
+ fork := true
+ )
+```
+
+{% endtab %}
+
+{% tab 'Mill' %}
+
+В файле `build.sc` вы можете добавить зависимость от Cask:
+
+```scala
+object example extends RootModule with ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps = Agg(
+ ivy"com.lihaoyi::cask::0.10.2"
+ )
+}
+```
+{% endtab %}
+
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/_markdown/_ru/install-munit.md b/_includes/_markdown/_ru/install-munit.md
new file mode 100644
index 0000000000..aa15142558
--- /dev/null
+++ b/_includes/_markdown/_ru/install-munit.md
@@ -0,0 +1,68 @@
+{% altDetails install-info-box 'Установка MUnit' %}
+
+{% tabs munit-unit-test-1 class=tabs-build-tool %}
+{% tab 'Scala CLI' %}
+
+Вы можете запросить весь набор инструментов одной командой:
+
+```scala
+//> using toolkit latest
+```
+
+MUnit, будучи тестовым фреймворком, доступен только в тестовых файлах:
+файлах в каталоге `test` или тех, которые имеют расширение `.test.scala`.
+Подробнее о тестовой области (test scope) см. [в документации Scala CLI](https://scala-cli.virtuslab.org/docs/commands/test/).
+
+В качестве альтернативы вы можете запросить только определенную версию MUnit:
+
+```scala
+//> using dep org.scalameta::munit:1.1.0
+```
+
+{% endtab %}
+
+{% tab 'sbt' %}
+
+В файле `build.sbt` вы можете добавить зависимость от toolkit-test:
+
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit-test" % "0.7.0" % Test
+ )
+```
+
+Здесь конфигурация `Test` означает, что зависимость используется только исходными файлами в `src/test`.
+
+В качестве альтернативы вы можете запросить только определенную версию MUnit:
+
+```scala
+libraryDependencies += "org.scalameta" %% "munit" % "1.1.0" % Test
+```
+{% endtab %}
+
+{% tab 'Mill' %}
+
+В файле `build.sc` вы можете добавить объект `test`, расширяющий `Tests` и `TestModule.Munit`:
+
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ object test extends Tests with TestModule.Munit {
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit-test:0.7.0"
+ )
+ }
+}
+```
+
+В качестве альтернативы вы можете запросить только определенную версию MUnit:
+
+```scala
+ivy"org.scalameta::munit:1.1.0"
+```
+{% endtab %}
+{% endtabs %}
+{% endaltDetails %}
\ No newline at end of file
diff --git a/_includes/_markdown/_ru/install-os-lib.md b/_includes/_markdown/_ru/install-os-lib.md
new file mode 100644
index 0000000000..f010d1f7fd
--- /dev/null
+++ b/_includes/_markdown/_ru/install-os-lib.md
@@ -0,0 +1,64 @@
+{% altDetails require-info-box 'Установка OS-Lib' %}
+
+{% tabs oslib-install class=tabs-build-tool %}
+
+{% tab 'Scala CLI' %}
+
+Вы можете запросить весь набор инструментов одной командой:
+
+```scala
+//> using toolkit latest
+```
+
+В качестве альтернативы вы можете запросить только определенную версию OS-Lib:
+
+```scala
+//> using dep com.lihaoyi::os-lib:0.11.3
+```
+
+{% endtab %}
+
+{% tab 'sbt' %}
+
+В файле `build.sbt` вы можете добавить зависимость от `toolkit`:
+
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit" % "0.7.0"
+ )
+```
+
+В качестве альтернативы вы можете запросить только определенную версию OS-Lib:
+
+```scala
+libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.11.3"
+```
+
+{% endtab %}
+
+{% tab 'Mill' %}
+
+В файле `build.sc` вы можете добавить зависимость от `toolkit`:
+
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit:0.7.0"
+ )
+}
+```
+
+В качестве альтернативы вы можете запросить только определенную версию OS-Lib:
+
+```scala
+ivy"com.lihaoyi::os-lib:0.11.3"
+```
+
+{% endtab %}
+
+{% endtabs %}
+{% endaltDetails %}
\ No newline at end of file
diff --git a/_includes/_markdown/_ru/install-sttp.md b/_includes/_markdown/_ru/install-sttp.md
new file mode 100644
index 0000000000..fec7938cea
--- /dev/null
+++ b/_includes/_markdown/_ru/install-sttp.md
@@ -0,0 +1,64 @@
+
+{% altDetails install-info-box 'Установка sttp' %}
+
+{% tabs sttp-install-methods class=tabs-build-tool%}
+
+{% tab 'Scala CLI' %}
+
+Вы можете запросить весь набор инструментов одной командой:
+
+```scala
+//> using toolkit latest
+```
+
+В качестве альтернативы вы можете запросить только определенную версию sttp:
+
+```scala
+//> using dep com.softwaremill.sttp.client4::core:4.0.0-RC1
+```
+
+{% endtab %}
+
+{% tab 'sbt' %}
+
+В файле `build.sbt` вы можете добавить зависимость от `toolkit`:
+
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit" % "0.7.0"
+ )
+```
+
+В качестве альтернативы вы можете запросить только определенную версию sttp:
+
+```scala
+libraryDependencies += "com.softwaremill.sttp.client4" %% "core" % "4.0.0-RC1"
+```
+
+{% endtab %}
+
+{% tab 'Mill' %}
+
+В файле `build.sc` вы можете добавить зависимость от `toolkit`:
+
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit:0.7.0"
+ )
+}
+```
+
+В качестве альтернативы вы можете запросить только определенную версию sttp:
+
+```scala
+ivy"com.softwaremill.sttp.client4::core:4.0.0-RC1"
+```
+
+{% endtab %}
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/_markdown/_ru/install-upickle.md b/_includes/_markdown/_ru/install-upickle.md
new file mode 100644
index 0000000000..83880a91a8
--- /dev/null
+++ b/_includes/_markdown/_ru/install-upickle.md
@@ -0,0 +1,64 @@
+
+{% altDetails install-info-box 'Установка upickle' %}
+
+{% tabs upickle-install-methods class=tabs-build-tool %}
+
+{% tab 'Scala CLI' %}
+
+Вы можете запросить весь набор инструментов одной командой:
+
+```scala
+//> using toolkit latest
+```
+
+В качестве альтернативы вы можете запросить только определенную версию UPickle:
+
+```scala
+//> using dep com.lihaoyi::upickle:4.1.0
+```
+
+{% endtab %}
+
+{% tab 'sbt' %}
+
+В файле `build.sbt` вы можете добавить зависимость от `toolkit`:
+
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit" % "0.7.0"
+ )
+```
+
+В качестве альтернативы вы можете запросить только определенную версию UPickle:
+
+```scala
+libraryDependencies += "com.lihaoyi" %% "upickle" % "4.1.0"
+```
+
+{% endtab %}
+
+{% tab 'Mill' %}
+
+В файле `build.sc` вы можете добавить зависимость от `toolkit`:
+
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit:0.7.0"
+ )
+}
+```
+
+В качестве альтернативы вы можете запросить только определенную версию UPickle:
+
+```scala
+ivy"com.lihaoyi::upickle:4.1.0"
+```
+
+{% endtab %}
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/_markdown/courses-coursera.md b/_includes/_markdown/courses-coursera.md
new file mode 100644
index 0000000000..403c5e3100
--- /dev/null
+++ b/_includes/_markdown/courses-coursera.md
@@ -0,0 +1,18 @@
+## Scala Courses on Coursera by EPFL
+
+The [Scala Center](https://scala.epfl.ch) at EPFL offers free online courses of various levels, from beginner to advanced.
+
+For beginners:
+
+- [Effective Programming in Scala](https://www.coursera.org/learn/effective-scala): a practical introduction to Scala for professional developers
+- [Functional Programming Principles in Scala](https://www.coursera.org/learn/scala-functional-programming): the foundational course by Martin Odersky, Scala's creator
+
+More advanced topics:
+
+- [Functional Program Design in Scala](https://www.coursera.org/learn/scala-functional-program-design): builds on functional principles with more advanced concepts
+- [Parallel Programming](https://www.coursera.org/learn/scala-parallel-programming)
+- [Big Data Analysis with Scala and Spark](https://www.coursera.org/learn/scala-spark-big-data)
+- [Programming Reactive Systems](https://www.coursera.org/learn/scala-akka-reactive): introduces Akka, actors and reactive streams
+
+All courses are free to audit, with an option to pay for a certificate, to showcase your skills on your resume or LinkedIn.
+For more on Scala Center's online courses, visit [this page](https://docs.scala-lang.org/online-courses.html#learning-platforms).
diff --git a/_includes/_markdown/courses-extension-school.md b/_includes/_markdown/courses-extension-school.md
new file mode 100644
index 0000000000..003c42a4f2
--- /dev/null
+++ b/_includes/_markdown/courses-extension-school.md
@@ -0,0 +1,9 @@
+## EPFL Extension School: Effective Programming in Scala
+
+Subscribing to [Effective programming in Scala](https://www.epfl.ch/education/continuing-education/effective-programming-in-scala/) on the EPFL Extension School offers:
+
+- Regular Q&A sessions and code reviews with experts from the Scala team
+- An [Extension School certificate](https://www.epfl.ch/education/continuing-education/certifications/) upon completion
+
+This course combines video lessons, written content and hands-on exercise focused on practical aspects, including business domain modeling, error handling, data manipulation, and task parallelization.
+For more on Scala Center's online courses, visit [this page](https://docs.scala-lang.org/online-courses.html#learning-platforms).
diff --git a/_includes/_markdown/courses-rock-the-jvm.md b/_includes/_markdown/courses-rock-the-jvm.md
new file mode 100644
index 0000000000..0b0db4f9f1
--- /dev/null
+++ b/_includes/_markdown/courses-rock-the-jvm.md
@@ -0,0 +1,17 @@
+## Rock the JVM Courses
+
+_As part of a partnership with the Scala Center, Rock the JVM donates 30% of the revenue from any courses purchased through the links in this section to support the Scala Center._
+
+[Rock the JVM](https://rockthejvm.com?affcode=256201_r93i1xuv) is a learning platform with free and premium courses on the Scala language, and all major libraries and tools in the Scala ecosystem: Typelevel, Zio, Akka/Pekko, Spark, and others.
+Its main Scala courses are:
+
+- [Scala at Light Speed](https://rockthejvm.com/courses/scala-at-light-speed?affcode=256201_r93i1xuv) (free)
+- [Scala & Functional Programming Essentials](https://rockthejvm.com/courses/scala-essentials?affcode=256201_r93i1xuv) (premium)
+- [Advanced Scala and Functional Programming](https://rockthejvm.com/courses/advanced-scala?affcode=256201_r93i1xuv) (premium)
+- [Scala Macros & Metaprogramming](https://rockthejvm.com/courses/scala-macros-and-metaprogramming?affcode=256201_r93i1xuv) (premium)
+
+Other courses teach how to build full-stack Scala applications, using [Typelevel](https://rockthejvm.com/courses/typelevel-rite-of-passage?affcode=256201_r93i1xuv) or [ZIO](https://rockthejvm.com/courses/zio-rite-of-passage?affcode=256201_r93i1xuv) ecosystems.
+
+
+
+Explore more premium [courses](https://rockthejvm.com/courses?affcode=256201_r93i1xuv) or check out [free video tutorials](https://youtube.com/rockthejvm?affcode=256201_r93i1xuv) and [free articles](https://rockthejvm.com/articles?affcode=256201_r93i1xuv).
diff --git a/_includes/_markdown/install-cask.md b/_includes/_markdown/install-cask.md
new file mode 100644
index 0000000000..3637ddfac9
--- /dev/null
+++ b/_includes/_markdown/install-cask.md
@@ -0,0 +1,37 @@
+{% altDetails require-info-box 'Getting Cask' %}
+
+{% tabs cask-install class=tabs-build-tool %}
+
+{% tab 'Scala CLI' %}
+You can declare a dependency on Cask with the following `using` directive:
+```scala
+//> using dep com.lihaoyi::cask::0.10.2
+```
+{% endtab %}
+
+{% tab 'sbt' %}
+In your `build.sbt`, you can add a dependency on Cask:
+```scala
+lazy val example = project.in(file("example"))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "com.lihaoyi" %% "cask" % "0.10.2",
+ fork := true
+ )
+```
+{% endtab %}
+
+{% tab 'Mill' %}
+In your `build.sc`, you can add a dependency on Cask:
+```scala
+object example extends RootModule with ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps = Agg(
+ ivy"com.lihaoyi::cask::0.10.2"
+ )
+}
+```
+{% endtab %}
+
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/_markdown/install-munit.md b/_includes/_markdown/install-munit.md
new file mode 100644
index 0000000000..47eeb1509f
--- /dev/null
+++ b/_includes/_markdown/install-munit.md
@@ -0,0 +1,53 @@
+{% altDetails install-info-box 'Getting MUnit' %}
+
+{% tabs munit-unit-test-1 class=tabs-build-tool %}
+{% tab 'Scala CLI' %}
+You can require the entire toolkit in a single line:
+```scala
+//> using toolkit latest
+```
+MUnit, being a testing framework, is only available in test files: files in a `test` directory or ones that have the `.test.scala` extension. Refer to the [Scala CLI documentation](https://scala-cli.virtuslab.org/docs/commands/test/) to learn more about the test scope.
+
+Alternatively, you can require just a specific version of MUnit:
+```scala
+//> using dep org.scalameta::munit:1.1.0
+```
+{% endtab %}
+{% tab 'sbt' %}
+In your build.sbt file, you can add the dependency on toolkit-test:
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit-test" % "0.7.0" % Test
+ )
+```
+
+Here the `Test` configuration means that the dependency is only used by the source files in `src/test`.
+
+Alternatively, you can require just a specific version of MUnit:
+```scala
+libraryDependencies += "org.scalameta" %% "munit" % "1.1.0" % Test
+```
+{% endtab %}
+{% tab 'Mill' %}
+In your build.sc file, you can add a `test` object extending `Tests` and `TestModule.Munit`:
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ object test extends Tests with TestModule.Munit {
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit-test:0.7.0"
+ )
+ }
+}
+```
+
+Alternatively, you can require just a specific version of MUnit:
+```scala
+ivy"org.scalameta::munit:1.1.0"
+```
+{% endtab %}
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/_markdown/install-os-lib.md b/_includes/_markdown/install-os-lib.md
new file mode 100644
index 0000000000..ae254d9d71
--- /dev/null
+++ b/_includes/_markdown/install-os-lib.md
@@ -0,0 +1,46 @@
+{% altDetails require-info-box 'Getting OS-Lib' %}
+
+{% tabs oslib-install class=tabs-build-tool %}
+{% tab 'Scala CLI' %}
+You can require the entire toolkit in a single line:
+```scala
+//> using toolkit latest
+```
+
+Alternatively, you can require just a specific version of OS-Lib:
+```scala
+//> using dep com.lihaoyi::os-lib:0.11.3
+```
+{% endtab %}
+{% tab 'sbt' %}
+In your `build.sbt`, you can add a dependency on the toolkit:
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit" % "0.7.0"
+ )
+```
+Alternatively, you can require just a specific version of OS-Lib:
+```scala
+libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.11.3"
+```
+{% endtab %}
+{% tab 'Mill' %}
+In your `build.sc` file, you can add a dependency on the Toolkit:
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit:0.7.0"
+ )
+}
+```
+Alternatively, you can require just a specific version of OS-Lib:
+```scala
+ivy"com.lihaoyi::os-lib:0.11.3"
+```
+{% endtab %}
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/_markdown/install-sttp.md b/_includes/_markdown/install-sttp.md
new file mode 100644
index 0000000000..0173ec47e1
--- /dev/null
+++ b/_includes/_markdown/install-sttp.md
@@ -0,0 +1,47 @@
+{% altDetails install-info-box 'Getting sttp' %}
+
+{% tabs sttp-install-methods class=tabs-build-tool%}
+{% tab 'Scala CLI' %}
+You can require the entire toolkit in a single line:
+```scala
+//> using toolkit latest
+```
+
+Alternatively, you can require just a specific version of sttp:
+```scala
+//> using dep com.softwaremill.sttp.client4::core:4.0.0-RC1
+```
+{% endtab %}
+{% tab 'sbt' %}
+In your build.sbt file, you can add a dependency on the Toolkit:
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit" % "0.7.0"
+ )
+```
+
+Alternatively, you can require just a specific version of sttp:
+```scala
+libraryDependencies += "com.softwaremill.sttp.client4" %% "core" % "4.0.0-RC1"
+```
+{% endtab %}
+{% tab 'Mill' %}
+In your build.sc file, you can add a dependency on the Toolkit:
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit:0.7.0"
+ )
+}
+```
+Alternatively, you can require just a specific version of sttp:
+```scala
+ivy"com.softwaremill.sttp.client4::core:4.0.0-RC1"
+```
+{% endtab %}
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/_markdown/install-upickle.md b/_includes/_markdown/install-upickle.md
new file mode 100644
index 0000000000..9f9cff8a62
--- /dev/null
+++ b/_includes/_markdown/install-upickle.md
@@ -0,0 +1,46 @@
+{% altDetails install-info-box 'Getting upickle' %}
+
+{% tabs upickle-install-methods class=tabs-build-tool %}
+{% tab 'Scala CLI' %}
+Using Scala CLI, you can require the entire toolkit in a single line:
+```scala
+//> using toolkit latest
+```
+
+Alternatively, you can require just a specific version of UPickle:
+```scala
+//> using dep com.lihaoyi::upickle:4.1.0
+```
+{% endtab %}
+{% tab 'sbt' %}
+In your build.sbt file, you can add the dependency on the Toolkit:
+```scala
+lazy val example = project.in(file("."))
+ .settings(
+ scalaVersion := "3.4.2",
+ libraryDependencies += "org.scala-lang" %% "toolkit" % "0.7.0"
+ )
+```
+Alternatively, you can require just a specific version of UPickle:
+```scala
+libraryDependencies += "com.lihaoyi" %% "upickle" % "4.1.0"
+```
+{% endtab %}
+{% tab 'Mill' %}
+In your build.sc file, you can add the dependency to the upickle library:
+```scala
+object example extends ScalaModule {
+ def scalaVersion = "3.4.2"
+ def ivyDeps =
+ Agg(
+ ivy"org.scala-lang::toolkit:0.7.0"
+ )
+}
+```
+Alternatively, you can require just a specific version of UPickle:
+```scala
+ivy"com.lihaoyi::upickle:4.1.0"
+```
+{% endtab %}
+{% endtabs %}
+{% endaltDetails %}
diff --git a/_includes/alert-banner.html b/_includes/alert-banner.html
new file mode 100644
index 0000000000..94c5ac1273
--- /dev/null
+++ b/_includes/alert-banner.html
@@ -0,0 +1,10 @@
+{% comment %}use the variable 'message' to include markdown text to display in the alert.{% endcomment %}
+
+{% unless include.message_id == 'disabled' %}
+
+
diff --git a/_includes/column-list-of-items.html b/_includes/column-list-of-items.html
deleted file mode 100644
index eb9e1600be..0000000000
--- a/_includes/column-list-of-items.html
+++ /dev/null
@@ -1,18 +0,0 @@
-{% comment %}
- Layouts using this include should pass an include variable called 'collection' referencing a collection carrying the data (i.e.: contribute_community_tickets, contribute_resources...)
-{% endcomment %}
-