From a884c0b838e13680008a05b756be256cf1eedd9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Sat, 17 Sep 2022 19:30:17 +0300 Subject: [PATCH 01/14] Add scala 3 book in russian --- _overviews/scala3-book/introduction.md | 1 + _ru/overviews/scala3-book/introduction.md | 34 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 _ru/overviews/scala3-book/introduction.md diff --git a/_overviews/scala3-book/introduction.md b/_overviews/scala3-book/introduction.md index 8533dca2b5..27cee362a9 100644 --- a/_overviews/scala3-book/introduction.md +++ b/_overviews/scala3-book/introduction.md @@ -5,6 +5,7 @@ description: This page begins the overview documentation of the Scala 3 language num: 1 previous-page: next-page: scala-features +languages: [ru] --- Welcome to the Scala 3 Book. diff --git a/_ru/overviews/scala3-book/introduction.md b/_ru/overviews/scala3-book/introduction.md new file mode 100644 index 0000000000..9c81a1b64f --- /dev/null +++ b/_ru/overviews/scala3-book/introduction.md @@ -0,0 +1,34 @@ +--- +title: Введение +type: chapter +description: На этой странице начинается обзорная документация по языку Scala 3. +num: 1 +previous-page: +next-page: scala-features +--- + +Добро пожаловать в книгу Scala 3. +Цель этой книги — предоставить неформальное введение в язык Scala. +Она относительно легко затрагивает все темы Scala. +Если в какой-то момент во время чтения этой книги вы захотите получить дополнительную информацию о конкретной функции, +вы найдете ссылки на нашу [Справочную документацию][reference], +в которой более подробно рассматриваются многие новые функции языка Scala. + +
+  If you are interested in the archived Scala 2 edition of the book, you +can access it here. We are currently in the process of +merging the two books and you can help us. +
+ +Over the course of this book, we hope to demonstrate that Scala is a beautiful, expressive programming language, with a clean, modern syntax, which supports functional programming (FP) and object-oriented programming (OOP), and that provides a safe static type system. +Scala’s syntax, grammar, and features have been re-thought, debated in an open process, and updated in 2020 to be clearer and easier to understand than ever before. + +The book begins with a whirlwind tour of many of Scala’s features in the [“A Taste of Scala” section][taste]. +After that tour, the sections that follow it provide more details on those language features. + +{% comment %} +We should have a link structure on the whole tour here +{% endcomment %} + +[reference]: {{ site.scala3ref }}/overview.html +[taste]: {% link _overviews/scala3-book/taste-intro.md %} From 88c283a0baa975f1ffe34f3388e57a9998a3fa56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Tue, 20 Sep 2022 19:27:13 +0300 Subject: [PATCH 02/14] Add scala 3 book in russian --- _ru/overviews/scala3-book/introduction.md | 34 -- _ru/scala3/book/introduction.md | 38 ++ _ru/scala3/book/scala-features.md | 583 ++++++++++++++++++++++ _ru/scala3/book/taste-intro.md | 29 ++ _ru/scala3/book/why-scala-3.md | 499 ++++++++++++++++++ 5 files changed, 1149 insertions(+), 34 deletions(-) delete mode 100644 _ru/overviews/scala3-book/introduction.md create mode 100644 _ru/scala3/book/introduction.md create mode 100644 _ru/scala3/book/scala-features.md create mode 100644 _ru/scala3/book/taste-intro.md create mode 100644 _ru/scala3/book/why-scala-3.md diff --git a/_ru/overviews/scala3-book/introduction.md b/_ru/overviews/scala3-book/introduction.md deleted file mode 100644 index 9c81a1b64f..0000000000 --- a/_ru/overviews/scala3-book/introduction.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Введение -type: chapter -description: На этой странице начинается обзорная документация по языку Scala 3. -num: 1 -previous-page: -next-page: scala-features ---- - -Добро пожаловать в книгу Scala 3. -Цель этой книги — предоставить неформальное введение в язык Scala. -Она относительно легко затрагивает все темы Scala. -Если в какой-то момент во время чтения этой книги вы захотите получить дополнительную информацию о конкретной функции, -вы найдете ссылки на нашу [Справочную документацию][reference], -в которой более подробно рассматриваются многие новые функции языка Scala. - -
-  If you are interested in the archived Scala 2 edition of the book, you -can access it here. We are currently in the process of -merging the two books and you can help us. -
- -Over the course of this book, we hope to demonstrate that Scala is a beautiful, expressive programming language, with a clean, modern syntax, which supports functional programming (FP) and object-oriented programming (OOP), and that provides a safe static type system. -Scala’s syntax, grammar, and features have been re-thought, debated in an open process, and updated in 2020 to be clearer and easier to understand than ever before. - -The book begins with a whirlwind tour of many of Scala’s features in the [“A Taste of Scala” section][taste]. -After that tour, the sections that follow it provide more details on those language features. - -{% comment %} -We should have a link structure on the whole tour here -{% endcomment %} - -[reference]: {{ site.scala3ref }}/overview.html -[taste]: {% link _overviews/scala3-book/taste-intro.md %} diff --git a/_ru/scala3/book/introduction.md b/_ru/scala3/book/introduction.md new file mode 100644 index 0000000000..f958a663f4 --- /dev/null +++ b/_ru/scala3/book/introduction.md @@ -0,0 +1,38 @@ +--- +layout: multipage-overview +title: Введение +scala3: true +partof: scala3-book +overview-name: "Scala 3 — Book" +type: chapter +description: На этой странице начинается обзорная документация по языку Scala 3. +language: ru +num: 1 +previous-page: +next-page: scala-features +--- + +Добро пожаловать в книгу по Scala 3. +Цель этой книги — предоставить неформальное введение в язык Scala. +Она относительно легко затрагивает все темы Scala. +Если в какой-то момент во время чтения этой книги вы захотите получить дополнительную информацию о конкретной функции, +можете воспользоваться ссылкой на нашу [Справочную документацию][reference], +в которой более подробно рассматриваются многие новые функции языка Scala. + +
+  Если вас интересует заархивированное издание книги для Scala 2, +доступ к нему можно получить здесь. +В настоящее время мы находимся в процессе слияния двух книг, и вы можете нам помочь. +
+ +В этой книге мы надеемся продемонстрировать, что Scala — это красивый, выразительный язык программирования с чистым современным синтаксисом, +который поддерживает и функциональное программирование (FP), и объектно-ориентированное программирование (ООП), +а также обеспечивает безопасную статическую систему типов. +Синтаксис, грамматика и функции Scala были переосмыслены, открыто обсуждались и были обновлены в 2020 году, +чтобы стать яснее и проще для понимания, чем когда-либо прежде. + +Книга начинается с беглого обзора возможностей Scala в [разделе “Почувствуй Scala”][taste]. +После этого обзора в следующих разделах содержится более подробная информация о рассмотренных языковых функциях. + +[reference]: {{ site.scala3ref }}/overview.html +[taste]: /ru/scala3/book/taste-intro.html diff --git a/_ru/scala3/book/scala-features.md b/_ru/scala3/book/scala-features.md new file mode 100644 index 0000000000..de43c1eaf1 --- /dev/null +++ b/_ru/scala3/book/scala-features.md @@ -0,0 +1,583 @@ +--- +layout: multipage-overview +title: Возможности Scala +partof: scala3-book +overview-name: Scala 3 — Book +type: chapter +description: На этой странице рассматриваются основные возможности языка программирования Scala. +language: ru +num: 2 +previous-page: introduction +next-page: why-scala-3 +--- + + +Название _Scala_ происходит от слова _scalable_, и в соответствии с этим названием язык Scala используется для +поддержки загруженных веб-сайтов и анализа огромных наборов данных. +В этом разделе представлены функции, которые делают Scala масштабируемым языком. +Эти функции разделены на три раздела: + +- Функции высокоуровневого языка программирования +- Функции низкоуровневого языка программирования +- Особенности экосистемы Scala + + + +{% comment %} +I think of this section as being like an “elevator pitch.” +{% endcomment %} + +## High-level features + +Looking at Scala from the proverbial “30,000 foot view,” you can make the following statements about it: + +- It’s a high-level programming language +- It has a concise, readable syntax +- It’s statically-typed (but feels dynamic) +- It has an expressive type system +- It’s a functional programming (FP) language +- It’s an object-oriented programming (OOP) language +- It supports the fusion of FP and OOP +- Contextual abstractions provide a clear way to implement _term inference_ +- It runs on the JVM (and in the browser) +- It interacts seamlessly with Java code +- It’s used for server-side applications (including microservices), big data applications, and can also be used in the browser with Scala.js + +The following sections take a quick look at these features. + + +### A high-level language + +Scala is considered a high-level language in at least two ways. +First, like Java and many other modern languages, you don’t deal with low-level concepts like pointers and memory management. + +Second, with the use of lambdas and higher-order functions, you write your code at a very high level. +As the functional programming saying goes, in Scala you write _what_ you want, not _how_ to achieve it. +That is, we don’t write imperative code like this: + +{% tabs scala-features-1 class=tabs-scala-version %} +{% tab 'Scala 2' for=scala-features-1 %} +```scala +import scala.collection.mutable.ListBuffer + +def double(ints: List[Int]): List[Int] = { + val buffer = new ListBuffer[Int]() + for (i <- ints) { + buffer += i * 2 + } + buffer.toList +} + +val oldNumbers = List(1, 2, 3) +val newNumbers = double(oldNumbers) +``` +{% endtab %} +{% tab 'Scala 3' for=scala-features-1 %} +```scala +import scala.collection.mutable.ListBuffer + +def double(ints: List[Int]): List[Int] = + val buffer = new ListBuffer[Int]() + for i <- ints do + buffer += i * 2 + buffer.toList + +val oldNumbers = List(1, 2, 3) +val newNumbers = double(oldNumbers) +``` +{% endtab %} +{% endtabs %} + +That code instructs the compiler what to do on a step-by-step basis. +Instead, we write high-level, functional code using higher-order functions and lambdas like this to compute the same result: + +{% tabs scala-features-2 %} +{% tab 'Scala 2 and 3' for=scala-features-2 %} +```scala +val newNumbers = oldNumbers.map(_ * 2) +``` +{% endtab %} +{% endtabs %} + + +As you can see, that code is much more concise, easier to read, and easier to maintain. + + +### Concise syntax + +Scala has a concise, readable syntax. +For instance, variables are created concisely, and their types are clear: + +{% tabs scala-features-3 %} +{% tab 'Scala 2 and 3' for=scala-features-3 %} +```scala +val nums = List(1,2,3) +val p = Person("Martin", "Odersky") +``` +{% endtab %} +{% endtabs %} + + +Higher-order functions and lambdas make for concise code that’s readable: + +{% tabs scala-features-4 %} +{% tab 'Scala 2 and 3' for=scala-features-4 %} +```scala +nums.map(i => i * 2) // long form +nums.map(_ * 2) // short form + +nums.filter(i => i > 1) +nums.filter(_ > 1) +``` +{% endtab %} +{% endtabs %} + +Traits, classes, and methods are defined with a clean, light syntax: + +{% tabs scala-features-5 class=tabs-scala-version %} +{% tab 'Scala 2' for=scala-features-5 %} +```scala mdoc +trait Animal { + def speak(): Unit +} + +trait HasTail { + def wagTail(): Unit +} + +class Dog extends Animal with HasTail { + def speak(): Unit = println("Woof") + def wagTail(): Unit = println("⎞⎜⎛ ⎞⎜⎛") +} +``` +{% endtab %} +{% tab 'Scala 3' for=scala-features-5 %} +```scala +trait Animal: + def speak(): Unit + +trait HasTail: + def wagTail(): Unit + +class Dog extends Animal, HasTail: + def speak(): Unit = println("Woof") + def wagTail(): Unit = println("⎞⎜⎛ ⎞⎜⎛") +``` +{% endtab %} +{% endtabs %} + + +Studies have shown that the time a developer spends _reading_ code to _writing_ code is at least a 10:1 ratio, so writing code that is concise _and_ readable is important. + + +### A dynamic feel + +Scala is a statically-typed language, but thanks to its type inference capabilities it feels dynamic. +All of these expressions look like a dynamically-typed language like Python or Ruby, but they’re all Scala: + +{% tabs scala-features-6 class=tabs-scala-version %} +{% tab 'Scala 2' for=scala-features-6 %} +```scala +val s = "Hello" +val p = Person("Al", "Pacino") +val sum = nums.reduceLeft(_ + _) +val y = for (i <- nums) yield i * 2 +val z = nums + .filter(_ > 100) + .filter(_ < 10_000) + .map(_ * 2) +``` +{% endtab %} +{% tab 'Scala 3' for=scala-features-6 %} +```scala +val s = "Hello" +val p = Person("Al", "Pacino") +val sum = nums.reduceLeft(_ + _) +val y = for i <- nums yield i * 2 +val z = nums + .filter(_ > 100) + .filter(_ < 10_000) + .map(_ * 2) +``` +{% endtab %} +{% endtabs %} + + +As Heather Miller states, Scala is considered to be a [strong, statically-typed language](https://heather.miller.am/blog/types-in-scala.html), and you get all the benefits of static types: + +- Correctness: you catch most errors at compile-time +- Great IDE support + - Reliable code completion + - Catching errors at compile-time means catching mistakes as you type + - Easy and reliable refactoring +- You can refactor your code with confidence +- Method type declarations tell readers what the method does, and help serve as documentation +- Scalability and maintainability: types help ensure correctness across arbitrarily large applications and development teams +- Strong typing in combination with excellent inference enables mechanisms like [contextual abstraction]({{ site.scala3ref }}/contextual) that allows you to omit boilerplate code. Often, this boilerplate code can be inferred by the compiler, based on type definitions and a given context. + +{% comment %} +In that list: +- 'Correctness' and 'Scalability' come from Heather Miller’s page +- the IDE-related quotes in this section come from the Scala.js website: + - catch most errors in the IDE + - Easy and reliable refactoring + - Reliable code completion +{% endcomment %} + + +### Expressive type system + +{% comment %} +- this text comes from the current [ScalaTour](https://docs.scala-lang.org/tour/tour-of-scala.html). +- TODO: all of the URLs will have to be updated + +- i removed these items until we can replace them: +* [Compound types](/tour/compound-types.html) +* [conversions](/tour/implicit-conversions.html) +* [Explicitly typed self references](/tour/self-types.html) +{% endcomment %} + +Scala’s type system enforces, at compile-time, that abstractions are used in a safe and coherent manner. +In particular, the type system supports: + +- [Inferred types]({% link _overviews/scala3-book/types-inferred.md %}) +- [Generic classes]({% link _overviews/scala3-book/types-generics.md %}) +- [Variance annotations]({% link _overviews/scala3-book/types-variance.md %}) +- [Upper](/tour/upper-type-bounds.html) and [lower](/tour/lower-type-bounds.html) type bounds +- [Polymorphic methods](/tour/polymorphic-methods.html) +- [Intersection types]({% link _overviews/scala3-book/types-intersection.md %}) +- [Union types]({% link _overviews/scala3-book/types-union.md %}) +- [Type lambdas]({{ site.scala3ref }}/new-types/type-lambdas.html) +- [`given` instances and `using` clauses]({% link _overviews/scala3-book/ca-given-using-clauses.md %}) +- [Extension methods]({% link _overviews/scala3-book/ca-extension-methods.md %}) +- [Type classes]({% link _overviews/scala3-book/ca-type-classes.md %}) +- [Multiversal equality]({% link _overviews/scala3-book/ca-multiversal-equality.md %}) +- [Opaque type aliases]({% link _overviews/scala3-book/types-opaque-types.md %}) +- [Open classes]({{ site.scala3ref }}/other-new-features/open-classes.html) +- [Match types]({{ site.scala3ref }}/new-types/match-types.html) +- [Dependent function types]({{ site.scala3ref }}/new-types/dependent-function-types.html) +- [Polymorphic function types]({{ site.scala3ref }}/new-types/polymorphic-function-types.html) +- [Context bounds]({{ site.scala3ref }}/contextual/context-bounds.html) +- [Context functions]({{ site.scala3ref }}/contextual/context-functions.html) +- [Inner classes](/tour/inner-classes.html) and [abstract type members](/tour/abstract-type-members.html) as object members + +In combination, these features provide a powerful basis for the safe reuse of programming abstractions and for the type-safe extension of software. + + +### A functional programming language + +Scala is a functional programming (FP) language, meaning: + +- Functions are values, and can be passed around like any other value +- Higher-order functions are directly supported +- Lambdas are built in +- Everything in Scala is an expression that returns a value +- Syntactically it’s easy to use immutable variables, and their use is encouraged +- It has a wealth of immutable collection classes in the standard library +- Those collection classes come with dozens of functional methods: they don’t mutate the collection, but instead return an updated copy of the data + + +### An object-oriented language + +Scala is an object-oriented programming (OOP) language. +Every value is an instance of a class and every “operator” is a method. + +In Scala, all types inherit from a top-level class `Any`, whose immediate children are `AnyVal` (_value types_, such as `Int` and `Boolean`) and `AnyRef` (_reference types_, as in Java). +This means that the Java distinction between primitive types and boxed types (e.g. `int` vs. `Integer`) isn’t present in Scala. +Boxing and unboxing is completely transparent to the user. + +{% comment %} +- AnyRef above is wrong in case of strict null checking, no? On the other hand, maybe too much information to state this here +- probably not worth to mention (too advanced at this point) there is AnyKind +- Add the “types hierarchy” image here? +{% endcomment %} + + +### Supports FP/OOP fusion + +{% comment %} +NOTE: This text in the first line comes from this slide: https://twitter.com/alexelcu/status/996408359514525696 +{% endcomment %} + +The essence of Scala is the fusion of functional programming and object-oriented programming in a typed setting: + +- Functions for the logic +- Objects for the modularity + +As [Martin Odersky has stated](https://jaxenter.com/current-state-scala-odersky-interview-129495.html), “Scala was designed to show that a fusion of functional and object-oriented programming is possible and practical.” + + +### Term inference, made clearer + +Following Haskell, Scala was the second popular language to have some form of _implicits_. +In Scala 3 these concepts have been completely re-thought and more clearly implemented. + +The core idea is _term inference_: Given a type, the compiler synthesizes a “canonical” term that has that type. +In Scala, a context parameter directly leads to an inferred argument term that could also be written down explicitly. + +Use cases for this concept include implementing [type classes]({% link _overviews/scala3-book/ca-type-classes.md %}), establishing context, dependency injection, expressing capabilities, computing new types, and proving relationships between them. + +Scala 3 makes this process more clear than ever before. +Read about contextual abstractions in the [Reference documentation]({{ site.scala3ref }}/contextual). + + +### Client & server + +Scala code runs on the Java Virtual Machine (JVM), so you get all of its benefits: + +- Security +- Performance +- Memory management +- Portability and platform independence +- The ability to use the wealth of existing Java and JVM libraries + +In addition to running on the JVM, Scala also runs in the browser with Scala.js (and open source third-party tools to integrate popular JavaScript libraries), and native executables can be built with Scala Native and GraalVM. + + +### Seamless Java interaction + +You can use Java classes and libraries in your Scala applications, and you can use Scala code in your Java applications. +In regards to the second point, large libraries like [Akka](https://akka.io) and the [Play Framework](https://www.playframework.com) are written in Scala, and can be used in Java applications. + +In regards to the first point, Java classes and libraries are used in Scala applications every day. +For instance, in Scala you can read files with a Java `BufferedReader` and `FileReader`: + +{% tabs scala-features-7 %} +{% tab 'Scala 2 and 3' for=scala-features-7 %} +```scala +import java.io.* +val br = BufferedReader(FileReader(filename)) +// read the file with `br` ... +``` +{% endtab %} +{% endtabs %} + +Using Java code in Scala is generally seamless. + +Java collections can also be used in Scala, and if you want to use Scala’s rich collection class methods with them, you can convert them with just a few lines of code: + +{% tabs scala-features-8 %} +{% tab 'Scala 2 and 3' for=scala-features-8 %} +```scala +import scala.jdk.CollectionConverters.* +val scalaList: Seq[Integer] = JavaClass.getJavaList().asScala.toSeq +``` +{% endtab %} +{% endtabs %} + + +### Wealth of libraries + +As you’ll see in the third section of this page, Scala libraries and frameworks like these have been written to power busy websites and work with huge datasets: + +1. The [Play Framework](https://www.playframework.com) is a lightweight, stateless, developer-friendly, web-friendly architecture for creating highly-scalable applications +2. [Lagom](https://www.lagomframework.com) is a microservices framework that helps you decompose your legacy monolith and build, test, and deploy entire systems of reactive microservices +3. [Apache Spark](https://spark.apache.org) is a unified analytics engine for big data processing, with built-in modules for streaming, SQL, machine learning and graph processing + +The [Awesome Scala list](https://github.com/lauris/awesome-scala) shows dozens of additional open source tools that developers have created to build Scala applications. + +In addition to server-side programming, [Scala.js](https://www.scala-js.org) is a strongly-typed replacement for writing JavaScript, with open source third-party libraries that include tools to integrate with Facebook’s React library, jQuery, and more. + + + +{% comment %} +The Lower-Level Features section is like the second part of an elevator pitch. +Assuming you told someone about the previous high-level features and then they say, “Tell me more,” this is what you might tell them. +{% endcomment %} + +## Lower-level language features + +Where the previous section covered high-level features of Scala, it’s interesting to note that at a high level you can make the same statements about both Scala 2 and Scala 3. +A decade ago Scala started with a strong foundation of desirable features, and as you’ll see in this section, those benefits have been improved with Scala 3. + +At a “sea level” view of the details---i.e., the language features programmers use everyday---Scala 3 has significant advantages over Scala 2: + +- The ability to create algebraic data types (ADTs) more concisely with enums +- An even more concise and readable syntax: + - The “quiet” control structure syntax is easier to read + - Optional braces + - Fewer symbols in the code creates less visual noise, making it easier to read + - The `new` keyword is generally no longer needed when creating class instances + - The formality of package objects have been dropped in favor of simpler “top level” definitions +- A grammar that’s more clear: + - Multiple different uses of the `implicit` keyword have been removed; those uses are replaced by more obvious keywords like `given`, `using`, and `extension`, focusing on intent over mechanism (see the [Givens][givens] section for details) + - [Extension methods][extension] replace implicit classes with a clearer and simpler mechanism + - The addition of the `open` modifier for classes makes the developer intentionally declare that a class is open for modification, thereby limiting ad-hoc extensions to a code base + - [Multiversal equality][multiversal] rules out nonsensical comparisons with `==` and `!=` (i.e., attempting to compare a `Person` to a `Planet`) + - Macros are implemented much more easily + - Union and intersection offer a flexible way to model types + - Trait parameters replace and simplify early initializers + - [Opaque type aliases][opaque_types] replace most uses of value classes, while guaranteeing the absence of boxing + - Export clauses provide a simple and general way to express aggregation, which can replace the previous facade pattern of package objects inheriting from classes + - The procedure syntax has been dropped, and the varargs syntax has been changed, both to make the language more consistent + - The `@infix` annotation makes it obvious how you want a method to be applied + - The [`@targetName`]({{ site.scala3ref }}/other-new-features/targetName.html) method annotation defines an alternate name for the method, improving Java interoperability, and letting you provide aliases for symbolic operators + +It would take too much space to demonstrate all of those features here, but follow the links in the items above to see those features in action. +All of these features are discussed in detail in the *New*, *Changed*, and *Dropped* features pages in the [Overview documentation][reference]. + + + +{% comment %} +CHECKLIST OF ALL ADDED, UPDATED, AND REMOVED FEATURES +===================================================== + +New Features +------------ +- trait parameters +- super traits +- creator applications +- export clauses +- opaque type aliases +- open classes +- parameter untupling +- kind polymorphism +- tupled function +- threadUnsafe annotation +- new control syntax +- optional braces (experimental) +- explicit nulls +- safe initialization + +CHANGED FEATURES +---------------- +- numeric literals +- structural types +- operators +- wildcard types +- type checking +- type inference +- implicit resolution +- implicit conversions +- overload resolution +- match expressions +- vararg patterns +- pattern bindings +- pattern matching +- eta expansion +- compiler plugins +- lazy vals initialization +- main functions + +DROPPED FEATURES +---------------- +- DelayedInit +- macros +- existential types +- type projection +- do/while syntax +- procedure syntax +- package objects +- early initializers +- class shadowing +- limit 22 +- XML literals +- symbol literals +- auto-application +- weak conformance +- nonlocal returns +- [this] qualifier + - private[this] and protected[this] access modifiers are deprecated + and will be phased out +{% endcomment %} + + + + +## Scala ecosystem + +{% comment %} +TODO: I didn’t put much work into this section because I don’t know if you want + to add many tools because (a) that can be seen as an endorsement and + (b) it creates a section that can need more maintenance than average + since tool popularity can wax and wane. One way to avoid the first + point is to base the lists on Github stars and activity. +{% endcomment %} + +Scala has a vibrant ecosystem, with libraries and frameworks for every need. +The [“Awesome Scala” list](https://github.com/lauris/awesome-scala) provides a list of hundreds of open source projects that are available to Scala developers, and the [Scaladex](https://index.scala-lang.org) provides a searchable index of Scala libraries. +Some of the more notable libraries are listed below. + + + +### Web development + +- The [Play Framework](https://www.playframework.com) followed the Ruby on Rails model to become a lightweight, stateless, developer-friendly, web-friendly architecture for highly-scalable applications +- [Scalatra](https://scalatra.org) is a tiny, high-performance, async web framework, inspired by Sinatra +- [Finatra](https://twitter.github.io/finatra) is Scala services built on TwitterServer and Finagle +- [Scala.js](https://www.scala-js.org) is a strongly-typed replacement for JavaScript that provides a safer way to build robust front-end web applications +- [ScalaJs-React](https://github.com/japgolly/scalajs-react) lifts Facebook’s React library into Scala.js, and endeavours to make it as type-safe and Scala-friendly as possible +- [Lagom](https://www.lagomframework.com) is a microservices framework that helps you decompose your legacy monolith and build, test, and deploy entire systems of Reactive microservices + +HTTP(S) libraries: + +- [Akka-http](https://akka.io) +- [Finch](https://github.com/finagle/finch) +- [Http4s](https://github.com/http4s/http4s) +- [Sttp](https://github.com/softwaremill/sttp) + +JSON libraries: + +- [Argonaut](https://github.com/argonaut-io/argonaut) +- [Circe](https://github.com/circe/circe) +- [Json4s](https://github.com/json4s/json4s) +- [Play-JSON](https://github.com/playframework/play-json) + +Serialization: + +- [ScalaPB](https://github.com/scalapb/ScalaPB) + +### Science and data analysis: + +- [Algebird](https://github.com/twitter/algebird) +- [Spire](https://github.com/typelevel/spire) +- [Squants](https://github.com/typelevel/squants) + + +### Big data + +- [Apache Spark](https://github.com/apache/spark) +- [Apache Flink](https://github.com/apache/flink) + + +### AI, machine learning + +- [BigDL](https://github.com/intel-analytics/BigDL) (Distributed Deep Learning Framework for Apache Spark) for Apache Spark +- [TensorFlow Scala](https://github.com/eaplatanios/tensorflow_scala) + + +### Functional Programming & Functional Reactive Programming + +FP: + +- [Cats](https://github.com/typelevel/cats) +- [Zio](https://github.com/zio/zio) + +Functional reactive programming (FRP): + +- [fs2](https://github.com/typelevel/fs2) +- [monix](https://github.com/monix/monix) + + +### Build tools + +- [sbt](https://www.scala-sbt.org) +- [Gradle](https://gradle.org) +- [Mill](https://github.com/lihaoyi/mill) + + + +## Summary + +As this page shows, Scala has many terrific programming language features at a high level, at an everyday programming level, and through its developer ecosystem. + + + +[reference]: {{ site.scala3ref }}/overview.html +[multiversal]: {% link _overviews/scala3-book/ca-multiversal-equality.md %} +[extension]: {% link _overviews/scala3-book/ca-extension-methods.md %} +[givens]: {% link _overviews/scala3-book/ca-given-using-clauses.md %} +[opaque_types]: {% link _overviews/scala3-book/types-opaque-types.md %} + + + diff --git a/_ru/scala3/book/taste-intro.md b/_ru/scala3/book/taste-intro.md new file mode 100644 index 0000000000..672f076471 --- /dev/null +++ b/_ru/scala3/book/taste-intro.md @@ -0,0 +1,29 @@ +--- +layout: multipage-overview +title: Почувствуй Scala +partof: scala3-book +overview-name: Scala 3 — Book +type: chapter +description: В этой главе представлен общий обзор основных возможностей языка программирования Scala 3. +language: ru +num: 4 +previous-page: why-scala-3 +next-page: taste-hello-world +--- + + +В этой главе представлен краткий обзор основных возможностей языка программирования Scala 3. +After this initial tour, the rest of the book provides more details on these features, and the [Reference documentation][reference] provides _many_ more details. + +## Setting Up Scala + +Througout this chapter, and the rest of the book, we encourage you to try out the examples by either copying +them or typing them out manually. The tools necessary to follow along with the examples on your own computer +can be installed by following our [getting started guide][get-started]. + +> Alternatively you can run the examples in a web browser with [Scastie](https://scastie.scala-lang.org), a +> fully online editor and code-runner for Scala. + + +[reference]: {{ site.scala3ref }}/overview.html +[get-started]: {% link _getting-started/index.md %} diff --git a/_ru/scala3/book/why-scala-3.md b/_ru/scala3/book/why-scala-3.md new file mode 100644 index 0000000000..d6f12992f2 --- /dev/null +++ b/_ru/scala3/book/why-scala-3.md @@ -0,0 +1,499 @@ +--- +layout: multipage-overview +title: Почему Scala 3? +partof: scala3-book +overview-name: Scala 3 — Book +type: chapter +description: На этой странице описаны преимущества языка программирования Scala 3. +language: ru +num: 3 +previous-page: scala-features +next-page: taste-intro +--- + +Использование Scala, и Scala 3 в частности, дает много преимуществ. +Трудно перечислить их все, но “топ десять” может выглядеть так: + +1. Scala embraces a fusion of functional programming (FP) and object-oriented programming (OOP) +2. Scala is statically typed, but often feels like a dynamically typed language +3. Scala’s syntax is concise, but still readable; it’s often referred to as _expressive_ +4. _Implicits_ in Scala 2 were a defining feature, and they have been improved and simplified in Scala 3 +5. Scala integrates seamlessly with Java, so you can create projects with mixed Scala and Java code, and Scala code easily uses the thousands of existing Java libraries +6. Scala can be used on the server, and also in the browser with [Scala.js](https://www.scala-js.org) +7. The Scala standard library has dozens of pre-built, functional methods to save you time, and greatly reduce the need to write custom `for` loops and algorithms +8. “Best practices” are built into Scala, which favors immutability, anonymous functions, higher-order functions, pattern matching, classes that cannot be extended by default, and more +9. The Scala ecosystem offers the most modern FP libraries in the world +10. Strong type system + +## 1) FP/OOP fusion + +More than any other language, Scala supports a fusion of the FP and OOP paradigms. +As Martin Odersky has stated, the essence of Scala is a fusion of functional and object-oriented programming in a typed setting, with: + +- Functions for the logic, and +- Objects for the modularity + +Possibly some of the best examples of modularity are the classes in the standard library. +For instance, a `List` is defined as a class---technically it’s an abstract class---and a new instance is created like this: + +{% tabs list %} +{% tab 'Scala 2 and 3' for=list %} +```scala +val x = List(1, 2, 3) +``` +{% endtab %} +{% endtabs %} + +However, what appears to the programmer to be a simple `List` is actually built from a combination of several specialized types, including traits named `Iterable`, `Seq`, and `LinearSeq`. +Those types are similarly composed of other small, modular units of code. + +In addition to building a type like `List` from a series of modular traits, the `List` API also consists of dozens of other methods, many of which are higher-order functions: + +{% tabs list-methods %} +{% tab 'Scala 2 and 3' for=list-methods %} +```scala +val xs = List(1, 2, 3, 4, 5) + +xs.map(_ + 1) // List(2, 3, 4, 5, 6) +xs.filter(_ < 3) // List(1, 2) +xs.find(_ > 3) // Some(4) +xs.takeWhile(_ < 3) // List(1, 2) +``` +{% endtab %} +{% endtabs %} + +In those examples, the values in the list can’t be modified. +The `List` class is immutable, so all of those methods return new values, as shown by the data in each comment. + +## 2) A dynamic feel + +Scala’s _type inference_ often makes the language feel dynamically typed, even though it’s statically typed. +This is true with variable declaration: + +{% tabs dynamic %} +{% tab 'Scala 2 and 3' for=dynamic %} +```scala +val a = 1 +val b = "Hello, world" +val c = List(1,2,3,4,5) +val stuff = ("fish", 42, 1_234.5) +``` +{% endtab %} +{% endtabs %} + +It’s also true when passing anonymous functions to higher-order functions: + +{% tabs dynamic-hof %} +{% tab 'Scala 2 and 3' for=dynamic-hof %} +```scala +list.filter(_ < 4) +list.map(_ * 2) +list.filter(_ < 4) + .map(_ * 2) +``` +{% endtab %} +{% endtabs %} + +and when defining methods: + +{% tabs dynamic-method %} +{% tab 'Scala 2 and 3' for=dynamic-method %} +```scala +def add(a: Int, b: Int) = a + b +``` +{% endtab %} +{% endtabs %} + +This is more true than ever in Scala 3, such as when using [union types][union-types]: + +{% tabs union %} +{% tab 'Scala 3 Only' for=union %} +```scala +// union type parameter +def help(id: Username | Password) = + val user = id match + case Username(name) => lookupName(name) + case Password(hash) => lookupPassword(hash) + // more code here ... + +// union type value +val b: Password | Username = if (true) name else password +``` +{% endtab %} +{% endtabs %} + +## 3) Concise syntax + +Scala is a low ceremony, “concise but still readable” language. For instance, variable declaration is concise: + +{% tabs concise %} +{% tab 'Scala 2 and 3' for=concise %} +```scala +val a = 1 +val b = "Hello, world" +val c = List(1,2,3) +``` +{% endtab %} +{% endtabs %} + +Creating types like traits, classes, and enumerations are concise: + +{% tabs enum %} +{% tab 'Scala 3 Only' for=enum %} +```scala +trait Tail: + def wagTail(): Unit + def stopTail(): Unit + +enum Topping: + case Cheese, Pepperoni, Sausage, Mushrooms, Onions + +class Dog extends Animal, Tail, Legs, RubberyNose + +case class Person( + firstName: String, + lastName: String, + age: Int +) +``` +{% endtab %} +{% endtabs %} + +Higher-order functions are concise: + +{% tabs list-hof %} +{% tab 'Scala 2 and 3' for=list-hof %} + +```scala +list.filter(_ < 4) +list.map(_ * 2) +``` +{% endtab %} +{% endtabs %} + +All of these expressions and many more are concise, and still very readable: what we call _expressive_. + +## 4) Implicits, simplified + +Implicits in Scala 2 were a major distinguishing design feature. +They represented _the_ fundamental way to abstract over context, with a unified paradigm that served a great variety of use cases, among them: + +- Implementing [type classes]({% link _overviews/scala3-book/ca-type-classes.md %}) +- Establishing context +- Dependency injection +- Expressing capabilities + +Since then, other languages have adopted similar concepts, all of which are variants of the core idea of _term inference_: Given a type, the compiler synthesizes a “canonical” term that has that type. + +While implicits were a defining feature in Scala 2, their design has been greatly improved in Scala 3: + +- There’s a single way to define “given” values +- There’s a single way to introduce implicit parameters and arguments +- There’s a separate way to import givens that does not allow them to hide in a sea of normal imports +- There’s a single way to define an implicit conversion, which is clearly marked as such, and does not require special syntax + +Benefits of these changes include: + +- The new design avoids feature interactions and makes the language more consistent +- It makes implicits easier to learn and harder to abuse +- It greatly improves the clarity of the 95% of Scala programs that use implicits +- It has the potential to enable term inference in a principled way that’s also accessible and friendly + +These capabilities are described in detail in other sections, so see the [Contextual Abstraction introduction][contextual], and the section on [`given` and `using` clauses][given] for more details. + +## 5) Seamless Java integration + +Scala/Java interaction is seamless in many ways. +For instance: + +- You can use all of the thousands of Java libraries that are available in your Scala projects +- A Scala `String` is essentially a Java `String`, with additional capabilities added to it +- Scala seamlessly uses the date/time classes in the Java *java.time._* package + +You can also use Java collections classes in Scala, and to give them more functionality, Scala includes methods so you can transform them into Scala collections. + +While almost every interaction is seamless, the [“Interacting with Java” chapter][java] demonstrates how to use some features together better, including how to use: + +- Java collections in Scala +- Java `Optional` in Scala +- Java interfaces in Scala +- Scala collections in Java +- Scala `Option` in Java +- Scala traits in Java +- Scala methods that throw exceptions in Java code +- Scala varargs parameters in Java + +See that chapter for more details on these features. + +## 6) Client & server + +Scala can be used on the server side with terrific frameworks: + +- The [Play Framework](https://www.playframework.com) lets you build highly scalable server-side applications and microservices +- [Akka Actors](https://akka.io) let you use the actor model to greatly simplify distributed and concurrent software applications + +Scala can also be used in the browser with the [Scala.js project](https://www.scala-js.org), which is a type-safe replacement for JavaScript. +The Scala.js ecosystem [has dozens of libraries](https://www.scala-js.org/libraries) to let you use React, Angular, jQuery, and many other JavaScript and Scala libraries in the browser. + +In addition to those tools, the [Scala Native](https://github.com/scala-native/scala-native) project “is an optimizing ahead-of-time compiler and lightweight managed runtime designed specifically for Scala.” It lets you build “systems” style binary executable applications with plain Scala code, and also lets you use lower-level primitives. + +## 7) Standard library methods + +You will rarely ever need to write a custom `for` loop again, because the dozens of pre-built functional methods in the Scala standard library will both save you time, and help make code more consistent across different applications. + +The following examples show some of the built-in collections methods, and there are many in addition to these. +While these all use the `List` class, the same methods work with other collections classes like `Seq`, `Vector`, `LazyList`, `Set`, `Map`, `Array`, and `ArrayBuffer`. + +Here are some examples: + +{% tabs list-more %} +{% tab 'Scala 2 and 3' for=list-more %} +```scala +List.range(1, 3) // List(1, 2) +List.range(start = 1, end = 6, step = 2) // List(1, 3, 5) +List.fill(3)("foo") // List(foo, foo, foo) +List.tabulate(3)(n => n * n) // List(0, 1, 4) +List.tabulate(4)(n => n * n) // List(0, 1, 4, 9) + +val a = List(10, 20, 30, 40, 10) // List(10, 20, 30, 40, 10) +a.distinct // List(10, 20, 30, 40) +a.drop(2) // List(30, 40, 10) +a.dropRight(2) // List(10, 20, 30) +a.dropWhile(_ < 25) // List(30, 40, 10) +a.filter(_ < 25) // List(10, 20, 10) +a.filter(_ > 100) // List() +a.find(_ > 20) // Some(30) +a.head // 10 +a.headOption // Some(10) +a.init // List(10, 20, 30, 40) +a.intersect(List(19,20,21)) // List(20) +a.last // 10 +a.lastOption // Some(10) +a.map(_ * 2) // List(20, 40, 60, 80, 20) +a.slice(2, 4) // List(30, 40) +a.tail // List(20, 30, 40, 10) +a.take(3) // List(10, 20, 30) +a.takeRight(2) // List(40, 10) +a.takeWhile(_ < 30) // List(10, 20) +a.filter(_ < 30).map(_ * 10) // List(100, 200, 100) + +val fruits = List("apple", "pear") +fruits.map(_.toUpperCase) // List(APPLE, PEAR) +fruits.flatMap(_.toUpperCase) // List(A, P, P, L, E, P, E, A, R) + +val nums = List(10, 5, 8, 1, 7) +nums.sorted // List(1, 5, 7, 8, 10) +nums.sortWith(_ < _) // List(1, 5, 7, 8, 10) +nums.sortWith(_ > _) // List(10, 8, 7, 5, 1) +``` +{% endtab %} +{% endtabs %} + +## 8) Built-in best practices + +Scala idioms encourage best practices in many ways. +For immutability, you’re encouraged to create immutable `val` declarations: + +{% tabs val %} +{% tab 'Scala 2 and 3' for=val %} +```scala +val a = 1 // immutable variable +``` +{% endtab %} +{% endtabs %} + +You’re also encouraged to use immutable collections classes like `List` and `Map`: + +{% tabs list-map %} +{% tab 'Scala 2 and 3' for=list-map %} +```scala +val b = List(1,2,3) // List is immutable +val c = Map(1 -> "one") // Map is immutable +``` +{% endtab %} +{% endtabs %} + +Case classes are primarily intended for use in [domain modeling]({% link _overviews/scala3-book/domain-modeling-intro.md %}), and their parameters are immutable: + +{% tabs case-class %} +{% tab 'Scala 2 and 3' for=case-class %} +```scala +case class Person(name: String) +val p = Person("Michael Scott") +p.name // Michael Scott +p.name = "Joe" // compiler error (reassignment to val name) +``` +{% endtab %} +{% endtabs %} + +As shown in the previous section, Scala collections classes support higher-order functions, and you can pass methods (not shown) and anonymous functions into them: + +{% tabs higher-order %} +{% tab 'Scala 2 and 3' for=higher-order %} +```scala +a.dropWhile(_ < 25) +a.filter(_ < 25) +a.takeWhile(_ < 30) +a.filter(_ < 30).map(_ * 10) +nums.sortWith(_ < _) +nums.sortWith(_ > _) +``` +{% endtab %} +{% endtabs %} + +`match` expressions let you use pattern matching, and they truly are _expressions_ that return values: + +{% tabs match class=tabs-scala-version %} +{% tab 'Scala 2' for=match %} +```scala +val numAsString = i match { + case 1 | 3 | 5 | 7 | 9 => "odd" + case 2 | 4 | 6 | 8 | 10 => "even" + case _ => "too big" +} +``` +{% endtab %} + +{% tab 'Scala 3' for=match %} +```scala +val numAsString = i match + case 1 | 3 | 5 | 7 | 9 => "odd" + case 2 | 4 | 6 | 8 | 10 => "even" + case _ => "too big" +``` +{% endtab %} +{% endtabs %} + +Because they can return values, they’re often used as the body of a method: + +{% tabs match-body class=tabs-scala-version %} +{% tab 'Scala 2' for=match-body %} +```scala +def isTruthy(a: Matchable) = a match { + case 0 | "" => false + case _ => true +} +``` +{% endtab %} + +{% tab 'Scala 3' for=match-body %} +```scala +def isTruthy(a: Matchable) = a match + case 0 | "" => false + case _ => true +``` +{% endtab %} +{% endtabs %} + +## 9) Ecosystem libraries + +Scala libraries for functional programming like [Cats](https://typelevel.org/cats) and [Zio](https://zio.dev) are leading-edge libraries in the FP community. +All of the buzzwords like high-performance, type safe, concurrent, asynchronous, resource-safe, testable, functional, modular, binary-compatible, efficient, effects/effectful, and more, can be said about these libraries. + +We could list hundreds of libraries here, but fortunately they’re all listed in another location: For those details, see the [“Awesome Scala” list](https://github.com/lauris/awesome-scala). + +## 10) Strong type system + +Scala has a strong type system, and it’s been improved even more in Scala 3. +Scala 3’s goals were defined early on, and those related to the type system include: + +- Simplification +- Eliminate inconsistencies +- Safety +- Ergonomics +- Performance + +_Simplification_ comes about through dozens of changed and dropped features. +For instance, the changes from the overloaded `implicit` keyword in Scala 2 to the terms `given` and `using` in Scala 3 make the language more clear, especially for beginning developers. + +_Eliminating inconsistencies_ is related to the dozens of [dropped features][dropped], [changed features][changed], and [added features][added] in Scala 3. +Some of the most important features in this category are: + +- Intersection types +- Union types +- Implicit function types +- Dependent function types +- Trait parameters +- Generic tuples + +{% comment %} +A list of types from the Dotty documentation: + +- Inferred types +- Generics +- Intersection types +- Union types +- Structural types +- Dependent function types +- Type classes +- Opaque types +- Variance +- Algebraic Data Types +- Wildcard arguments in types: ? replacing _ +- Type lambdas +- Match types +- Existential types +- Higher-kinded types +- Singleton types +- Refinement types +- Kind polymorphism +- Abstract type members and path-dependent types +- Dependent function types +- Bounds +{% endcomment %} + +_Safety_ is related to several new and changed features: + +- Multiversal equality +- Restricting implicit conversions +- Null safety +- Safe initialization + +Good examples of _ergonomics_ are enumerations and extension methods, which have been added to Scala 3 in a very readable manner: + +{% tabs extension %} +{% tab 'Scala 3 Only' for=extension %} +```scala +// enumeration +enum Color: + case Red, Green, Blue + +// extension methods +extension (c: Circle) + def circumference: Double = c.radius * math.Pi * 2 + def diameter: Double = c.radius * 2 + def area: Double = math.Pi * c.radius * c.radius +``` +{% endtab %} +{% endtabs %} + +_Performance_ relates to several areas. +One of those is [opaque types][opaque-types]. +In Scala 2 there were several attempts to create solutions to keep with the Domain-driven design (DDD) practice of giving values more meaningful types. +These attempts included: + +- Type aliases +- Value classes +- Case classes + +Unfortunately all of these approaches had weaknesses, as described in the [_Opaque Types_ SIP](https://docs.scala-lang.org/sips/opaque-types.html). +Conversely, the goal of opaque types, as described in that SIP, is that “operations on these wrapper types must not create any extra overhead at runtime while still providing a type safe use at compile time.” + +For more type system details, see the [Reference documentation][reference]. + +## Other great features + +Scala has many great features, and choosing a Top 10 list can be subjective. +Several surveys have shown that different groups of developers love different features. +Hopefully you’ll discover more great Scala features as you use the language. + +[java]: {% link _overviews/scala3-book/interacting-with-java.md %} +[given]: {% link _overviews/scala3-book/ca-given-using-clauses.md %} +[contextual]: {% link _overviews/scala3-book/ca-contextual-abstractions-intro.md %} +[reference]: {{ site.scala3ref }} +[dropped]: {{ site.scala3ref }}/dropped-features +[changed]: {{ site.scala3ref }}/changed-features +[added]:{{ site.scala3ref }}/other-new-features + +[union-types]: {% link _overviews/scala3-book/types-union.md %} +[opaque-types]: {% link _overviews/scala3-book/types-opaque-types.md %} From edff51ac79eeaa0fec7d4e679984fbf274b07f71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Wed, 21 Sep 2022 08:55:56 +0300 Subject: [PATCH 03/14] Add scala 3 book in russian --- _overviews/scala3-book/ca-context-bounds.md | 1 + _overviews/scala3-book/scala-features.md | 1 + _overviews/scala3-book/taste-intro.md | 1 + _overviews/scala3-book/why-scala-3.md | 1 + _ru/scala3/book/ca-context-bounds.md | 48 +++++++++++++++++++++ _ru/scala3/book/scala-features.md | 3 +- _ru/scala3/book/taste-intro.md | 3 +- _ru/scala3/book/why-scala-3.md | 3 +- 8 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 _ru/scala3/book/ca-context-bounds.md diff --git a/_overviews/scala3-book/ca-context-bounds.md b/_overviews/scala3-book/ca-context-bounds.md index b42f71e56d..15b3f7acbb 100644 --- a/_overviews/scala3-book/ca-context-bounds.md +++ b/_overviews/scala3-book/ca-context-bounds.md @@ -5,6 +5,7 @@ description: This page demonstrates Context Bounds in Scala 3. num: 61 previous-page: types-type-classes next-page: ca-given-imports +languages: [ru] --- diff --git a/_overviews/scala3-book/scala-features.md b/_overviews/scala3-book/scala-features.md index 8c28e6c380..af25d75631 100644 --- a/_overviews/scala3-book/scala-features.md +++ b/_overviews/scala3-book/scala-features.md @@ -5,6 +5,7 @@ description: This page discusses the main features of the Scala programming lang num: 2 previous-page: introduction next-page: why-scala-3 +languages: [ru] --- diff --git a/_overviews/scala3-book/taste-intro.md b/_overviews/scala3-book/taste-intro.md index 9c189ab9a5..bb8684dae2 100644 --- a/_overviews/scala3-book/taste-intro.md +++ b/_overviews/scala3-book/taste-intro.md @@ -5,6 +5,7 @@ description: This chapter provides a high-level overview of the main features of num: 4 previous-page: why-scala-3 next-page: taste-hello-world +languages: [ru] --- diff --git a/_overviews/scala3-book/why-scala-3.md b/_overviews/scala3-book/why-scala-3.md index 3b7ea60c31..e794a0ca7c 100644 --- a/_overviews/scala3-book/why-scala-3.md +++ b/_overviews/scala3-book/why-scala-3.md @@ -5,6 +5,7 @@ description: This page describes the benefits of the Scala 3 programming languag num: 3 previous-page: scala-features next-page: taste-intro +languages: [ru] --- {% comment %} diff --git a/_ru/scala3/book/ca-context-bounds.md b/_ru/scala3/book/ca-context-bounds.md new file mode 100644 index 0000000000..c4829b712d --- /dev/null +++ b/_ru/scala3/book/ca-context-bounds.md @@ -0,0 +1,48 @@ +--- +layout: multipage-overview +title: Контекстные границы +scala3: true +partof: scala3-book +overview-name: "Scala 3 — Book" +type: chapter +description: На этой странице демонстрируются контекстные границы в Scala 3. +language: ru +num: 61 +previous-page: types-type-classes +next-page: ca-given-imports +--- + +Во многих ситуациях the name of a _context parameter_ doesn’t have to be mentioned explicitly, since it’s only used by the compiler in synthesized arguments for other context parameters. +In that case you don’t have to define a parameter name, and can just provide the parameter type. + + +## Background + +For example, this `maximum` method takes a _context parameter_ of type `Ord`, only to pass it on as an argument to `max`: + +```scala +def maximum[A](xs: List[A])(using ord: Ord[A]): A = + xs.reduceLeft(max(ord)) +``` + +In that code the parameter name `ord` isn’t actually required; it can be passed on as an inferred argument to `max`, so you just state that `maximum` uses the type `Ord[A]` without giving it a name: + +```scala +def maximum[A](xs: List[A])(using Ord[A]): A = + xs.reduceLeft(max) +``` + + +## Context bounds + +Given that background, a _context bound_ is a shorthand syntax for expressing the pattern of, “a context parameter that depends on a type parameter.” + +Using a context bound, the `maximum` method can be written like this: + +```scala +def maximum[A: Ord](xs: List[A]): A = xs.reduceLeft(max) +``` + +A bound like `: Ord` on a type parameter `A` of a method or class indicates a context parameter with `Ord[A]`. + +For more information about context bounds, see the [“What are context bounds?”](https://docs.scala-lang.org/tutorials/FAQ/context-bounds.html) section of the Scala FAQ. diff --git a/_ru/scala3/book/scala-features.md b/_ru/scala3/book/scala-features.md index de43c1eaf1..eb66a9c331 100644 --- a/_ru/scala3/book/scala-features.md +++ b/_ru/scala3/book/scala-features.md @@ -1,8 +1,9 @@ --- layout: multipage-overview title: Возможности Scala +scala3: true partof: scala3-book -overview-name: Scala 3 — Book +overview-name: "Scala 3 — Book" type: chapter description: На этой странице рассматриваются основные возможности языка программирования Scala. language: ru diff --git a/_ru/scala3/book/taste-intro.md b/_ru/scala3/book/taste-intro.md index 672f076471..cfb40c2c05 100644 --- a/_ru/scala3/book/taste-intro.md +++ b/_ru/scala3/book/taste-intro.md @@ -1,8 +1,9 @@ --- layout: multipage-overview title: Почувствуй Scala +scala3: true partof: scala3-book -overview-name: Scala 3 — Book +overview-name: "Scala 3 — Book" type: chapter description: В этой главе представлен общий обзор основных возможностей языка программирования Scala 3. language: ru diff --git a/_ru/scala3/book/why-scala-3.md b/_ru/scala3/book/why-scala-3.md index d6f12992f2..f2dee5d341 100644 --- a/_ru/scala3/book/why-scala-3.md +++ b/_ru/scala3/book/why-scala-3.md @@ -1,8 +1,9 @@ --- layout: multipage-overview title: Почему Scala 3? +scala3: true partof: scala3-book -overview-name: Scala 3 — Book +overview-name: "Scala 3 — Book" type: chapter description: На этой странице описаны преимущества языка программирования Scala 3. language: ru From 20d10996394ca87a50fee335b656d0777f4d82ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Wed, 21 Sep 2022 09:35:08 +0300 Subject: [PATCH 04/14] Fix localized contents --- _includes/sidebar-toc-multipage-overview.html | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/_includes/sidebar-toc-multipage-overview.html b/_includes/sidebar-toc-multipage-overview.html index 83890101ac..5511d96361 100644 --- a/_includes/sidebar-toc-multipage-overview.html +++ b/_includes/sidebar-toc-multipage-overview.html @@ -18,11 +18,10 @@
Contents
{% if pg.num and (page.partof == pg.partof) %} {% if page.language %} - {% assign prefix = page.language | prepend: '/' %} - {% assign localizedId = pg.id | prepend: prefix %} + {% assign localizedId = pg.id %} {% for lpg in site.[page.language] %} {% if lpg.id == localizedId %} -
  • {{ lpg.title }} +
  • {{ lpg.title }} {{ toc }}
  • {% endif %} {% endfor %} From 8c92b31f12403abc1c2f75d0ba2fab408c5ad52b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Wed, 21 Sep 2022 19:13:57 +0300 Subject: [PATCH 05/14] Add scala 3 book in russian --- _ru/scala3/book/ca-context-bounds.md | 48 ---------------------------- _ru/scala3/book/taste-intro.md | 2 +- 2 files changed, 1 insertion(+), 49 deletions(-) delete mode 100644 _ru/scala3/book/ca-context-bounds.md diff --git a/_ru/scala3/book/ca-context-bounds.md b/_ru/scala3/book/ca-context-bounds.md deleted file mode 100644 index c4829b712d..0000000000 --- a/_ru/scala3/book/ca-context-bounds.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -layout: multipage-overview -title: Контекстные границы -scala3: true -partof: scala3-book -overview-name: "Scala 3 — Book" -type: chapter -description: На этой странице демонстрируются контекстные границы в Scala 3. -language: ru -num: 61 -previous-page: types-type-classes -next-page: ca-given-imports ---- - -Во многих ситуациях the name of a _context parameter_ doesn’t have to be mentioned explicitly, since it’s only used by the compiler in synthesized arguments for other context parameters. -In that case you don’t have to define a parameter name, and can just provide the parameter type. - - -## Background - -For example, this `maximum` method takes a _context parameter_ of type `Ord`, only to pass it on as an argument to `max`: - -```scala -def maximum[A](xs: List[A])(using ord: Ord[A]): A = - xs.reduceLeft(max(ord)) -``` - -In that code the parameter name `ord` isn’t actually required; it can be passed on as an inferred argument to `max`, so you just state that `maximum` uses the type `Ord[A]` without giving it a name: - -```scala -def maximum[A](xs: List[A])(using Ord[A]): A = - xs.reduceLeft(max) -``` - - -## Context bounds - -Given that background, a _context bound_ is a shorthand syntax for expressing the pattern of, “a context parameter that depends on a type parameter.” - -Using a context bound, the `maximum` method can be written like this: - -```scala -def maximum[A: Ord](xs: List[A]): A = xs.reduceLeft(max) -``` - -A bound like `: Ord` on a type parameter `A` of a method or class indicates a context parameter with `Ord[A]`. - -For more information about context bounds, see the [“What are context bounds?”](https://docs.scala-lang.org/tutorials/FAQ/context-bounds.html) section of the Scala FAQ. diff --git a/_ru/scala3/book/taste-intro.md b/_ru/scala3/book/taste-intro.md index cfb40c2c05..9d29b4b147 100644 --- a/_ru/scala3/book/taste-intro.md +++ b/_ru/scala3/book/taste-intro.md @@ -9,7 +9,7 @@ description: В этой главе представлен общий обзор language: ru num: 4 previous-page: why-scala-3 -next-page: taste-hello-world +next-page: --- From 84551cf7069d6c5df7b7598c18a882e3bc0d480d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Wed, 21 Sep 2022 19:36:00 +0300 Subject: [PATCH 06/14] Add scala 3 book in russian --- _overviews/scala3-book/ca-context-bounds.md | 1 - _overviews/scala3-book/taste-hello-world.md | 1 + _ru/scala3/book/taste-hello-world.md | 201 ++++++++++++++++++++ _ru/scala3/book/taste-intro.md | 2 +- 4 files changed, 203 insertions(+), 2 deletions(-) create mode 100644 _ru/scala3/book/taste-hello-world.md diff --git a/_overviews/scala3-book/ca-context-bounds.md b/_overviews/scala3-book/ca-context-bounds.md index 15b3f7acbb..b42f71e56d 100644 --- a/_overviews/scala3-book/ca-context-bounds.md +++ b/_overviews/scala3-book/ca-context-bounds.md @@ -5,7 +5,6 @@ description: This page demonstrates Context Bounds in Scala 3. num: 61 previous-page: types-type-classes next-page: ca-given-imports -languages: [ru] --- diff --git a/_overviews/scala3-book/taste-hello-world.md b/_overviews/scala3-book/taste-hello-world.md index b43512cdf7..31355ab555 100644 --- a/_overviews/scala3-book/taste-hello-world.md +++ b/_overviews/scala3-book/taste-hello-world.md @@ -5,6 +5,7 @@ description: This section demonstrates a Scala 3 'Hello, World!' example. num: 5 previous-page: taste-intro next-page: taste-repl +languages: [ru] --- > **Hint**: in the following examples try picking your preferred Scala version. diff --git a/_ru/scala3/book/taste-hello-world.md b/_ru/scala3/book/taste-hello-world.md new file mode 100644 index 0000000000..da4b2d4c89 --- /dev/null +++ b/_ru/scala3/book/taste-hello-world.md @@ -0,0 +1,201 @@ +--- +layout: multipage-overview +title: Пример 'Hello, World!' +scala3: true +partof: scala3-book +overview-name: "Scala 3 — Book" +type: chapter +description: В этом примере демонстрируется пример 'Hello, World!' на Scala 3. +language: ru +num: 5 +previous-page: taste-intro +next-page: +--- + +> **Hint**: in the following examples try picking your preferred Scala version. +> + +## Your First Scala Program + + +A Scala “Hello, World!” example goes as follows. +First, put this code in a file named _hello.scala_: + + + +{% tabs hello-world-demo class=tabs-scala-version %} + +{% tab 'Scala 2' for=hello-world-demo %} +```scala +object hello { + def main(args: Array[String]) = { + println("Hello, World!") + } +} +``` +> In this code, we defined a method named `main`, inside a Scala `object` named `hello`. +> An `object` in Scala is similar to a `class`, but defines a singleton instance that you can pass around. +> `main` takes an input parameter named `args` that must be typed as `Array[String]`, (ignore `args` for now). + +{% endtab %} + +{% tab 'Scala 3' for=hello-world-demo %} +```scala +@main def hello() = println("Hello, World!") +``` +> In this code, `hello` is a method. +> It’s defined with `def`, and declared to be a “main” method with the `@main` annotation. +> It prints the `"Hello, World!"` string to standard output (STDOUT) using the `println` method. + +{% endtab %} + +{% endtabs %} + + +Next, compile the code with `scalac`: + +```bash +$ scalac hello.scala +``` + +If you’re coming to Scala from Java, `scalac` is just like `javac`, so that command creates several files: + + +{% tabs hello-world-outputs class=tabs-scala-version %} + +{% tab 'Scala 2' for=hello-world-outputs %} +```bash +$ ls -1 +hello$.class +hello.class +hello.scala +``` +{% endtab %} + +{% tab 'Scala 3' for=hello-world-outputs %} +```bash +$ ls -1 +hello$package$.class +hello$package.class +hello$package.tasty +hello.scala +hello.class +hello.tasty +``` +{% endtab %} + +{% endtabs %} + + +Like Java, the _.class_ files are bytecode files, and they’re ready to run in the JVM. + +Now you can run the `hello` method with the `scala` command: + +```bash +$ scala hello +Hello, World! +``` + +Assuming that worked, congratulations, you just compiled and ran your first Scala application. + +> More information about sbt and other tools that make Scala development easier can be found in the [Scala Tools][scala_tools] chapter. + +## Ask For User Input + +In our next example let's ask for the user's name before we greet them! + +There are several ways to read input from a command-line, but a simple way is to use the +`readLine` method in the _scala.io.StdIn_ object. To use it, you need to first import it, like this: + +{% tabs import-readline %} +{% tab 'Scala 2 and 3' for=import-readline %} +```scala +import scala.io.StdIn.readLine +``` +{% endtab %} +{% endtabs %} + +To demonstrate how this works, let’s create a little example. Put this source code in a file named _helloInteractive.scala_: + + +{% tabs hello-world-interactive class=tabs-scala-version %} + +{% tab 'Scala 2' for=hello-world-interactive %} +```scala +import scala.io.StdIn.readLine + +object helloInteractive { + + def main(args: Array[String]) = { + println("Please enter your name:") + val name = readLine() + + println("Hello, " + name + "!") + } + +} +``` +{% endtab %} + +{% tab 'Scala 3' for=hello-world-interactive %} +```scala +import scala.io.StdIn.readLine + +@main def helloInteractive() = + println("Please enter your name:") + val name = readLine() + + println("Hello, " + name + "!") +``` +{% endtab %} + +{% endtabs %} + + +In this code we save the result of `readLine` to a variable called `name`, we then +use the `+` operator on strings to join `"Hello, "` with `name` and `"!"`, making one single string value. + +> You can learn more about using `val` by reading [Variables and Data Types](/scala3/book/taste-vars-data-types.html). + +Then compile the code with `scalac`: + +```bash +$ scalac helloInteractive.scala +``` +Then run it with `scala helloInteractive`, this time the program will pause after asking for your name, +and wait until you type a name and press return on the keyboard, looking like this: + +```bash +$ scala helloInteractive +Please enter your name: +▌ +``` + +When you enter your name at the prompt, the final interaction should look like this: + +```bash +$ scala helloInteractive +Please enter your name: +Alvin Alexander +Hello, Alvin Alexander! +``` + +### A Note about Imports + +As you saw in this application, sometimes certain methods, or other kinds of definitions that we'll see later, +are not available unless you use an `import` clause like so: + +{% tabs import-readline-2 %} +{% tab 'Scala 2 and 3' for=import-readline-2 %} +```scala +import scala.io.StdIn.readLine +``` +{% endtab %} +{% endtabs %} + +Imports help you write code in a few ways: + - you can put code in multiple files, to help avoid clutter, and to help navigate large projects. + - you can use a code library, perhaps written by someone else, that has useful functionality + - you can know where a certain definition comes from (especially if it was not written in the current file). + +[scala_tools]: {% link _overviews/scala3-book/scala-tools.md %} diff --git a/_ru/scala3/book/taste-intro.md b/_ru/scala3/book/taste-intro.md index 9d29b4b147..cfb40c2c05 100644 --- a/_ru/scala3/book/taste-intro.md +++ b/_ru/scala3/book/taste-intro.md @@ -9,7 +9,7 @@ description: В этой главе представлен общий обзор language: ru num: 4 previous-page: why-scala-3 -next-page: +next-page: taste-hello-world --- From 7aab7fc232848c8b61578465cac38c596a79370c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Wed, 21 Sep 2022 20:09:09 +0300 Subject: [PATCH 07/14] Add scala 3 book in russian --- _ru/scala3/book/introduction.md | 4 +- _ru/scala3/book/scala-features.md | 105 ++++++++++++++---------------- 2 files changed, 50 insertions(+), 59 deletions(-) diff --git a/_ru/scala3/book/introduction.md b/_ru/scala3/book/introduction.md index f958a663f4..ae23a36516 100644 --- a/_ru/scala3/book/introduction.md +++ b/_ru/scala3/book/introduction.md @@ -26,7 +26,7 @@ next-page: scala-features В этой книге мы надеемся продемонстрировать, что Scala — это красивый, выразительный язык программирования с чистым современным синтаксисом, -который поддерживает и функциональное программирование (FP), и объектно-ориентированное программирование (ООП), +который поддерживает и функциональное программирование (ФП), и объектно-ориентированное программирование (ООП), а также обеспечивает безопасную статическую систему типов. Синтаксис, грамматика и функции Scala были переосмыслены, открыто обсуждались и были обновлены в 2020 году, чтобы стать яснее и проще для понимания, чем когда-либо прежде. @@ -35,4 +35,4 @@ next-page: scala-features После этого обзора в следующих разделах содержится более подробная информация о рассмотренных языковых функциях. [reference]: {{ site.scala3ref }}/overview.html -[taste]: /ru/scala3/book/taste-intro.html +[taste]: {% link _overviews/scala3-book/taste-intro.md %} diff --git a/_ru/scala3/book/scala-features.md b/_ru/scala3/book/scala-features.md index eb66a9c331..adb89aee55 100644 --- a/_ru/scala3/book/scala-features.md +++ b/_ru/scala3/book/scala-features.md @@ -24,37 +24,34 @@ next-page: why-scala-3 -{% comment %} -I think of this section as being like an “elevator pitch.” -{% endcomment %} - -## High-level features +## Высокоуровневые функции -Looking at Scala from the proverbial “30,000 foot view,” you can make the following statements about it: +Глядя на Scala с пресловутого “вида с высоты 30 000 фунтов”, вы можете сделать о нем следующие утверждения: -- It’s a high-level programming language -- It has a concise, readable syntax -- It’s statically-typed (but feels dynamic) -- It has an expressive type system -- It’s a functional programming (FP) language -- It’s an object-oriented programming (OOP) language -- It supports the fusion of FP and OOP -- Contextual abstractions provide a clear way to implement _term inference_ -- It runs on the JVM (and in the browser) -- It interacts seamlessly with Java code -- It’s used for server-side applications (including microservices), big data applications, and can also be used in the browser with Scala.js +- Это высокоуровневый язык программирования +- Он имеет краткий, читаемый синтаксис +- Он статически типизирован (но кажется динамичным) +- Имеет выразительную систему типов +- Это язык функционального программирования (ФП) +- Это язык объектно-ориентированного программирования (ООП) +- Он поддерживает слияние ФП и ООП +- Контекстные абстракции обеспечивают понятный способ реализации _вывода терминов_ (_term inference_) +- Он работает на JVM (и в браузере) +- Беспрепятственно взаимодействует с Java кодом +- Он используется для серверных приложений (включая микросервисы), приложений для работы с большими данными, а также может использоваться в браузере с помощью Scala.js -The following sections take a quick look at these features. +Эти функции кратко рассматриваются в следующих разделах. -### A high-level language +### Высокоуровневый язык -Scala is considered a high-level language in at least two ways. -First, like Java and many other modern languages, you don’t deal with low-level concepts like pointers and memory management. +Scala считается высокоуровневым языком как минимум по двум причинам. +Во-первых, подобно Java и многим другим современным языкам, вы не имеете дело с низкоуровневыми понятиями, +такими как указатели и управление памятью. -Second, with the use of lambdas and higher-order functions, you write your code at a very high level. -As the functional programming saying goes, in Scala you write _what_ you want, not _how_ to achieve it. -That is, we don’t write imperative code like this: +Во-вторых, с использованием лямбда-выражений и функций высшего порядка вы пишете свой код на очень высоком уровне. +Как говорится в функциональном программировании, в Scala вы пишете то, _что_ хотите, а не то, _как_ этого добиться. +То есть мы не пишем императивный код вот так: {% tabs scala-features-1 class=tabs-scala-version %} {% tab 'Scala 2' for=scala-features-1 %} @@ -89,8 +86,9 @@ val newNumbers = double(oldNumbers) {% endtab %} {% endtabs %} -That code instructs the compiler what to do on a step-by-step basis. -Instead, we write high-level, functional code using higher-order functions and lambdas like this to compute the same result: +Этот код шаг за шагом указывает компилятору, что делать. +Вместо этого мы пишем высокоуровневый функциональный код, используя функции высшего порядка и лямбда-выражения, +подобные этому, для вычисления того же результата: {% tabs scala-features-2 %} {% tab 'Scala 2 and 3' for=scala-features-2 %} @@ -101,13 +99,13 @@ val newNumbers = oldNumbers.map(_ * 2) {% endtabs %} -As you can see, that code is much more concise, easier to read, and easier to maintain. +Как видите, этот код намного лаконичнее, его легче читать и легче поддерживать. -### Concise syntax +### Лаконичный синтаксис -Scala has a concise, readable syntax. -For instance, variables are created concisely, and their types are clear: +Scala имеет краткий, удобочитаемый синтаксис. +Например, переменные создаются лаконично, а их типы понятны: {% tabs scala-features-3 %} {% tab 'Scala 2 and 3' for=scala-features-3 %} @@ -119,13 +117,13 @@ val p = Person("Martin", "Odersky") {% endtabs %} -Higher-order functions and lambdas make for concise code that’s readable: +Функции высшего порядка и лямбда-выражения делают код кратким и удобочитаемым: {% tabs scala-features-4 %} {% tab 'Scala 2 and 3' for=scala-features-4 %} ```scala -nums.map(i => i * 2) // long form -nums.map(_ * 2) // short form +nums.map(i => i * 2) // длинная форма +nums.map(_ * 2) // краткая форма nums.filter(i => i > 1) nums.filter(_ > 1) @@ -133,7 +131,7 @@ nums.filter(_ > 1) {% endtab %} {% endtabs %} -Traits, classes, and methods are defined with a clean, light syntax: +Трэйты, классы и методы определяются с помощью простого и легкого синтаксиса: {% tabs scala-features-5 class=tabs-scala-version %} {% tab 'Scala 2' for=scala-features-5 %} @@ -168,13 +166,14 @@ class Dog extends Animal, HasTail: {% endtabs %} -Studies have shown that the time a developer spends _reading_ code to _writing_ code is at least a 10:1 ratio, so writing code that is concise _and_ readable is important. +Исследования показали, что время, которое разработчик тратит на _чтение_ и _написание_ кода, составляет как минимум 10:1, +поэтому важно писать краткий и читабельный код. -### A dynamic feel +### Ощущение динамики -Scala is a statically-typed language, but thanks to its type inference capabilities it feels dynamic. -All of these expressions look like a dynamically-typed language like Python or Ruby, but they’re all Scala: +Scala — это язык со статической типизацией, но благодаря своим возможностям вывода типов он кажется динамичным. +Все эти выражения выглядят как языки с динамической типизацией, такие как Python или Ruby, но это все Scala: {% tabs scala-features-6 class=tabs-scala-version %} {% tab 'Scala 2' for=scala-features-6 %} @@ -204,26 +203,18 @@ val z = nums {% endtabs %} -As Heather Miller states, Scala is considered to be a [strong, statically-typed language](https://heather.miller.am/blog/types-in-scala.html), and you get all the benefits of static types: +Как утверждает Heather Miller, Scala считается [сильным языком со статической типизацией](https://heather.miller.am/blog/types-in-scala.html), +и вы получаете все преимущества статических типов: -- Correctness: you catch most errors at compile-time -- Great IDE support - - Reliable code completion - - Catching errors at compile-time means catching mistakes as you type - - Easy and reliable refactoring -- You can refactor your code with confidence -- Method type declarations tell readers what the method does, and help serve as documentation -- Scalability and maintainability: types help ensure correctness across arbitrarily large applications and development teams -- Strong typing in combination with excellent inference enables mechanisms like [contextual abstraction]({{ site.scala3ref }}/contextual) that allows you to omit boilerplate code. Often, this boilerplate code can be inferred by the compiler, based on type definitions and a given context. - -{% comment %} -In that list: -- 'Correctness' and 'Scalability' come from Heather Miller’s page -- the IDE-related quotes in this section come from the Scala.js website: - - catch most errors in the IDE - - Easy and reliable refactoring - - Reliable code completion -{% endcomment %} +- Корректность: вы обнаруживаете большинство ошибок во время компиляции +- Отличная поддержка IDE + - Надежное автодополнение кода + - Отлов ошибок во время компиляции означает отлов ошибок по мере написания + - Простой и надежный рефакторинг +- Вы можете уверенно рефакторить свой код +- Объявления типов методов сообщают читателям, что делает метод, и помогают служить документацией +- Масштабируемость и удобство обслуживания: типы помогают обеспечить корректность в произвольно больших приложениях и командах разработчиков +- Строгая типизация в сочетании с превосходным выводом типов позволяет использовать такие механизмы, как [контекстная абстракция]({{ site.scala3ref }}/contextual), которая позволяет вам опускать шаблонный код. Часто этот шаблонный код может быть выведен компилятором на основе определений типов и заданного контекста. ### Expressive type system From ce824b0d57c04a63b7185d301fd6a2ea7a96c686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Thu, 22 Sep 2022 20:12:38 +0300 Subject: [PATCH 08/14] Add scala 3 book in russian --- _ru/scala3/book/scala-features.md | 402 ++++++++++++------------------ 1 file changed, 157 insertions(+), 245 deletions(-) diff --git a/_ru/scala3/book/scala-features.md b/_ru/scala3/book/scala-features.md index adb89aee55..d70bde8758 100644 --- a/_ru/scala3/book/scala-features.md +++ b/_ru/scala3/book/scala-features.md @@ -217,136 +217,120 @@ val z = nums - Строгая типизация в сочетании с превосходным выводом типов позволяет использовать такие механизмы, как [контекстная абстракция]({{ site.scala3ref }}/contextual), которая позволяет вам опускать шаблонный код. Часто этот шаблонный код может быть выведен компилятором на основе определений типов и заданного контекста. -### Expressive type system +### Выразительная система типов -{% comment %} -- this text comes from the current [ScalaTour](https://docs.scala-lang.org/tour/tour-of-scala.html). -- TODO: all of the URLs will have to be updated +Система типов в Scala во время компиляции обеспечивает безопасное и согласованное использование абстракций. +В частности, система типов поддерживает: -- i removed these items until we can replace them: -* [Compound types](/tour/compound-types.html) -* [conversions](/tour/implicit-conversions.html) -* [Explicitly typed self references](/tour/self-types.html) -{% endcomment %} +- [Выводимые типы]({% link _overviews/scala3-book/types-inferred.md %}) +- [Generic классы]({% link _overviews/scala3-book/types-generics.md %}) +- [Аннотации вариантности]({% link _overviews/scala3-book/types-variance.md %}) +- [Верхняя](/tour/upper-type-bounds.html) и [нижняя](/tour/lower-type-bounds.html) границы типов +- [Полиморфные методы](/tour/polymorphic-methods.html) +- [Типы пересечения]({% link _overviews/scala3-book/types-intersection.md %}) +- [Типы объединения]({% link _overviews/scala3-book/types-union.md %}) +- [Лямбда-типы]({{ site.scala3ref }}/new-types/type-lambdas.html) +- [Экземпляры `given` и предложения `using`]({% link _overviews/scala3-book/ca-given-using-clauses.md %}) +- [Методы расширения]({% link _overviews/scala3-book/ca-extension-methods.md %}) +- [Типовые классы]({% link _overviews/scala3-book/ca-type-classes.md %}) +- [Многостороннее равенство]({% link _overviews/scala3-book/ca-multiversal-equality.md %}) +- [Псевдонимы непрозрачного типа]({% link _overviews/scala3-book/types-opaque-types.md %}) +- [Открытые классы]({{ site.scala3ref }}/other-new-features/open-classes.html) +- [Типы соответствия]({{ site.scala3ref }}/new-types/match-types.html) +- [Зависимые типы функций]({{ site.scala3ref }}/new-types/dependent-function-types.html) +- [Полиморфные функциональные типы]({{ site.scala3ref }}/new-types/polymorphic-function-types.html) +- [Контекстные границы]({{ site.scala3ref }}/contextual/context-bounds.html) +- [Контекстные функции]({{ site.scala3ref }}/contextual/context-functions.html) +- [Внутренние классы](/tour/inner-classes.html) и [элементы абстрактного типа](/tour/abstract-type-members.html) как элементы объекта -Scala’s type system enforces, at compile-time, that abstractions are used in a safe and coherent manner. -In particular, the type system supports: +В сочетании эти функции обеспечивают мощную основу для безопасного повторного использования программных абстракций +и для безопасного расширения программного обеспечения. -- [Inferred types]({% link _overviews/scala3-book/types-inferred.md %}) -- [Generic classes]({% link _overviews/scala3-book/types-generics.md %}) -- [Variance annotations]({% link _overviews/scala3-book/types-variance.md %}) -- [Upper](/tour/upper-type-bounds.html) and [lower](/tour/lower-type-bounds.html) type bounds -- [Polymorphic methods](/tour/polymorphic-methods.html) -- [Intersection types]({% link _overviews/scala3-book/types-intersection.md %}) -- [Union types]({% link _overviews/scala3-book/types-union.md %}) -- [Type lambdas]({{ site.scala3ref }}/new-types/type-lambdas.html) -- [`given` instances and `using` clauses]({% link _overviews/scala3-book/ca-given-using-clauses.md %}) -- [Extension methods]({% link _overviews/scala3-book/ca-extension-methods.md %}) -- [Type classes]({% link _overviews/scala3-book/ca-type-classes.md %}) -- [Multiversal equality]({% link _overviews/scala3-book/ca-multiversal-equality.md %}) -- [Opaque type aliases]({% link _overviews/scala3-book/types-opaque-types.md %}) -- [Open classes]({{ site.scala3ref }}/other-new-features/open-classes.html) -- [Match types]({{ site.scala3ref }}/new-types/match-types.html) -- [Dependent function types]({{ site.scala3ref }}/new-types/dependent-function-types.html) -- [Polymorphic function types]({{ site.scala3ref }}/new-types/polymorphic-function-types.html) -- [Context bounds]({{ site.scala3ref }}/contextual/context-bounds.html) -- [Context functions]({{ site.scala3ref }}/contextual/context-functions.html) -- [Inner classes](/tour/inner-classes.html) and [abstract type members](/tour/abstract-type-members.html) as object members -In combination, these features provide a powerful basis for the safe reuse of programming abstractions and for the type-safe extension of software. +### Язык функционального программирования +Scala — это язык функционального программирования (ФП), что означает: -### A functional programming language +- Функции — это значения, и их можно передавать, как и любое другое значение +- Напрямую поддерживаются функции высшего порядка +- Встроенные лямбда +- Все в Scala — это выражение, возвращающее значение +- Синтаксически легко использовать неизменяемые переменные, и их использование приветствуется +- В стандартной библиотеке языка содержится множество неизменяемых классов коллекций +- Эти классы коллекций поставляются с десятками функциональных методов: они не изменяют коллекцию, вместо этого возвращая обновленную копию данных -Scala is a functional programming (FP) language, meaning: -- Functions are values, and can be passed around like any other value -- Higher-order functions are directly supported -- Lambdas are built in -- Everything in Scala is an expression that returns a value -- Syntactically it’s easy to use immutable variables, and their use is encouraged -- It has a wealth of immutable collection classes in the standard library -- Those collection classes come with dozens of functional methods: they don’t mutate the collection, but instead return an updated copy of the data +### Объектно-ориентированный язык +Scala — это язык объектно-ориентированного программирования (ООП). +Каждое значение — это экземпляр класса, а каждый “оператор” — это метод. -### An object-oriented language +В Scala все типы наследуются от класса верхнего уровня `Any`, чьими непосредственными дочерними элементами являются `AnyVal` (_типы значений_, такие как `Int` и `Boolean`) и `AnyRef` (_ссылочные типы_, как в Java). +Это означает, что различие в Java между примитивными и упакованными типами (например, `int` против `Integer`) отсутствует в Scala. +Упаковка и распаковка полностью прозрачны для пользователя. -Scala is an object-oriented programming (OOP) language. -Every value is an instance of a class and every “operator” is a method. -In Scala, all types inherit from a top-level class `Any`, whose immediate children are `AnyVal` (_value types_, such as `Int` and `Boolean`) and `AnyRef` (_reference types_, as in Java). -This means that the Java distinction between primitive types and boxed types (e.g. `int` vs. `Integer`) isn’t present in Scala. -Boxing and unboxing is completely transparent to the user. +### Поддерживает слияние ФП/ООП -{% comment %} -- AnyRef above is wrong in case of strict null checking, no? On the other hand, maybe too much information to state this here -- probably not worth to mention (too advanced at this point) there is AnyKind -- Add the “types hierarchy” image here? -{% endcomment %} +Суть Scala заключается в слиянии функционального программирования и объектно-ориентированного программирования в типизированной среде: -### Supports FP/OOP fusion +- Функции для логики +- Объекты для модульности -{% comment %} -NOTE: This text in the first line comes from this slide: https://twitter.com/alexelcu/status/996408359514525696 -{% endcomment %} +[Как заявил Мартин Одерски](https://jaxenter.com/current-state-scala-odersky-interview-129495.html), “Scala был разработан, чтобы показать, что слияние функционального и объектно-ориентированного программирования возможно и практично”. -The essence of Scala is the fusion of functional programming and object-oriented programming in a typed setting: -- Functions for the logic -- Objects for the modularity +### Вывод терминов стал более понятным -As [Martin Odersky has stated](https://jaxenter.com/current-state-scala-odersky-interview-129495.html), “Scala was designed to show that a fusion of functional and object-oriented programming is possible and practical.” +После Haskell Scala был вторым популярным языком, в котором была некоторая форма неявных (_implicits_) выражений. +В Scala 3 эти концепции были полностью переосмыслены и реализованы более четко. +Основная идея заключается в _выводе терминов_: на основе заданного, компилятор синтезирует “канонический” термин, который имеет этот тип. +В Scala параметр контекста напрямую ведет к выводимому термину аргумента, который также может быть записан явно. -### Term inference, made clearer +Примеры использования этой концепции включают реализацию [типовых классов]({% link _overviews/scala3-book/ca-type-classes.md %}), +установление контекста, внедрение зависимостей, выражение возможностей, вычисление новых типов и доказательство отношений между ними. -Following Haskell, Scala was the second popular language to have some form of _implicits_. -In Scala 3 these concepts have been completely re-thought and more clearly implemented. +Scala 3 делает этот процесс более понятным, чем когда-либо прежде. +О контекстных абстракциях можно прочесть в [Справочной документации]({{ site.scala3ref }}/contextual). -The core idea is _term inference_: Given a type, the compiler synthesizes a “canonical” term that has that type. -In Scala, a context parameter directly leads to an inferred argument term that could also be written down explicitly. -Use cases for this concept include implementing [type classes]({% link _overviews/scala3-book/ca-type-classes.md %}), establishing context, dependency injection, expressing capabilities, computing new types, and proving relationships between them. +### Клиент & сервер -Scala 3 makes this process more clear than ever before. -Read about contextual abstractions in the [Reference documentation]({{ site.scala3ref }}/contextual). +Код Scala работает на виртуальной машине Java (JVM), поэтому вы получаете все ее преимущества: +- Безопасность +- Производительность +- Управление памятью +- Портативность и независимость от платформы +- Возможность использовать множество существующих Java и JVM библиотек -### Client & server +Помимо работы на JVM, Scala также работает в браузере с помощью Scala.js (и сторонних инструментов с открытым исходным кодом для интеграции популярных библиотек JavaScript), а собственные исполняемые файлы могут быть созданы с помощью Scala Native и GraalVM. -Scala code runs on the Java Virtual Machine (JVM), so you get all of its benefits: -- Security -- Performance -- Memory management -- Portability and platform independence -- The ability to use the wealth of existing Java and JVM libraries +### Беспрепятственное взаимодействие с Java -In addition to running on the JVM, Scala also runs in the browser with Scala.js (and open source third-party tools to integrate popular JavaScript libraries), and native executables can be built with Scala Native and GraalVM. +Вы можете использовать Java классы и библиотеки в своих приложениях Scala, а также код Scala в приложениях Java. +Что касается второго пункта, большие библиотеки, такие как [Akka](https://akka.io) и [Play Framework](https://www.playframework.com) написаны на Scala и могут использоваться в приложениях Java. - -### Seamless Java interaction - -You can use Java classes and libraries in your Scala applications, and you can use Scala code in your Java applications. -In regards to the second point, large libraries like [Akka](https://akka.io) and the [Play Framework](https://www.playframework.com) are written in Scala, and can be used in Java applications. - -In regards to the first point, Java classes and libraries are used in Scala applications every day. -For instance, in Scala you can read files with a Java `BufferedReader` and `FileReader`: +Что касается первого пункта, классы и библиотеки Java используются в приложениях Scala каждый день. +Например, в Scala вы можете читать файлы с помощью `BufferedReader` и `FileReader` из Java: {% tabs scala-features-7 %} {% tab 'Scala 2 and 3' for=scala-features-7 %} ```scala import java.io.* val br = BufferedReader(FileReader(filename)) -// read the file with `br` ... +// чтение файла в `br` ... ``` {% endtab %} {% endtabs %} -Using Java code in Scala is generally seamless. +Использование Java-кода в Scala, как правило, не вызывает затруднений. -Java collections can also be used in Scala, and if you want to use Scala’s rich collection class methods with them, you can convert them with just a few lines of code: +В Scala также можно использовать коллекции Java, и если вы хотите использовать с ними богатый набор методов классов коллекций Scala, +то можете преобразовать их с помощью всего нескольких строк кода: {% tabs scala-features-8 %} {% tab 'Scala 2 and 3' for=scala-features-8 %} @@ -358,200 +342,130 @@ val scalaList: Seq[Integer] = JavaClass.getJavaList().asScala.toSeq {% endtabs %} -### Wealth of libraries - -As you’ll see in the third section of this page, Scala libraries and frameworks like these have been written to power busy websites and work with huge datasets: - -1. The [Play Framework](https://www.playframework.com) is a lightweight, stateless, developer-friendly, web-friendly architecture for creating highly-scalable applications -2. [Lagom](https://www.lagomframework.com) is a microservices framework that helps you decompose your legacy monolith and build, test, and deploy entire systems of reactive microservices -3. [Apache Spark](https://spark.apache.org) is a unified analytics engine for big data processing, with built-in modules for streaming, SQL, machine learning and graph processing - -The [Awesome Scala list](https://github.com/lauris/awesome-scala) shows dozens of additional open source tools that developers have created to build Scala applications. - -In addition to server-side programming, [Scala.js](https://www.scala-js.org) is a strongly-typed replacement for writing JavaScript, with open source third-party libraries that include tools to integrate with Facebook’s React library, jQuery, and more. - - - -{% comment %} -The Lower-Level Features section is like the second part of an elevator pitch. -Assuming you told someone about the previous high-level features and then they say, “Tell me more,” this is what you might tell them. -{% endcomment %} - -## Lower-level language features - -Where the previous section covered high-level features of Scala, it’s interesting to note that at a high level you can make the same statements about both Scala 2 and Scala 3. -A decade ago Scala started with a strong foundation of desirable features, and as you’ll see in this section, those benefits have been improved with Scala 3. - -At a “sea level” view of the details---i.e., the language features programmers use everyday---Scala 3 has significant advantages over Scala 2: - -- The ability to create algebraic data types (ADTs) more concisely with enums -- An even more concise and readable syntax: - - The “quiet” control structure syntax is easier to read - - Optional braces - - Fewer symbols in the code creates less visual noise, making it easier to read - - The `new` keyword is generally no longer needed when creating class instances - - The formality of package objects have been dropped in favor of simpler “top level” definitions -- A grammar that’s more clear: - - Multiple different uses of the `implicit` keyword have been removed; those uses are replaced by more obvious keywords like `given`, `using`, and `extension`, focusing on intent over mechanism (see the [Givens][givens] section for details) - - [Extension methods][extension] replace implicit classes with a clearer and simpler mechanism - - The addition of the `open` modifier for classes makes the developer intentionally declare that a class is open for modification, thereby limiting ad-hoc extensions to a code base - - [Multiversal equality][multiversal] rules out nonsensical comparisons with `==` and `!=` (i.e., attempting to compare a `Person` to a `Planet`) - - Macros are implemented much more easily - - Union and intersection offer a flexible way to model types - - Trait parameters replace and simplify early initializers - - [Opaque type aliases][opaque_types] replace most uses of value classes, while guaranteeing the absence of boxing - - Export clauses provide a simple and general way to express aggregation, which can replace the previous facade pattern of package objects inheriting from classes - - The procedure syntax has been dropped, and the varargs syntax has been changed, both to make the language more consistent - - The `@infix` annotation makes it obvious how you want a method to be applied - - The [`@targetName`]({{ site.scala3ref }}/other-new-features/targetName.html) method annotation defines an alternate name for the method, improving Java interoperability, and letting you provide aliases for symbolic operators - -It would take too much space to demonstrate all of those features here, but follow the links in the items above to see those features in action. -All of these features are discussed in detail in the *New*, *Changed*, and *Dropped* features pages in the [Overview documentation][reference]. - - - -{% comment %} -CHECKLIST OF ALL ADDED, UPDATED, AND REMOVED FEATURES -===================================================== - -New Features ------------- -- trait parameters -- super traits -- creator applications -- export clauses -- opaque type aliases -- open classes -- parameter untupling -- kind polymorphism -- tupled function -- threadUnsafe annotation -- new control syntax -- optional braces (experimental) -- explicit nulls -- safe initialization - -CHANGED FEATURES ----------------- -- numeric literals -- structural types -- operators -- wildcard types -- type checking -- type inference -- implicit resolution -- implicit conversions -- overload resolution -- match expressions -- vararg patterns -- pattern bindings -- pattern matching -- eta expansion -- compiler plugins -- lazy vals initialization -- main functions - -DROPPED FEATURES ----------------- -- DelayedInit -- macros -- existential types -- type projection -- do/while syntax -- procedure syntax -- package objects -- early initializers -- class shadowing -- limit 22 -- XML literals -- symbol literals -- auto-application -- weak conformance -- nonlocal returns -- [this] qualifier - - private[this] and protected[this] access modifiers are deprecated - and will be phased out -{% endcomment %} - - - - -## Scala ecosystem - -{% comment %} -TODO: I didn’t put much work into this section because I don’t know if you want - to add many tools because (a) that can be seen as an endorsement and - (b) it creates a section that can need more maintenance than average - since tool popularity can wax and wane. One way to avoid the first - point is to base the lists on Github stars and activity. -{% endcomment %} - -Scala has a vibrant ecosystem, with libraries and frameworks for every need. -The [“Awesome Scala” list](https://github.com/lauris/awesome-scala) provides a list of hundreds of open source projects that are available to Scala developers, and the [Scaladex](https://index.scala-lang.org) provides a searchable index of Scala libraries. -Some of the more notable libraries are listed below. - - - -### Web development - -- The [Play Framework](https://www.playframework.com) followed the Ruby on Rails model to become a lightweight, stateless, developer-friendly, web-friendly architecture for highly-scalable applications -- [Scalatra](https://scalatra.org) is a tiny, high-performance, async web framework, inspired by Sinatra -- [Finatra](https://twitter.github.io/finatra) is Scala services built on TwitterServer and Finagle -- [Scala.js](https://www.scala-js.org) is a strongly-typed replacement for JavaScript that provides a safer way to build robust front-end web applications -- [ScalaJs-React](https://github.com/japgolly/scalajs-react) lifts Facebook’s React library into Scala.js, and endeavours to make it as type-safe and Scala-friendly as possible -- [Lagom](https://www.lagomframework.com) is a microservices framework that helps you decompose your legacy monolith and build, test, and deploy entire systems of Reactive microservices - -HTTP(S) libraries: +### Богатство библиотек + +Как будет видно в третьем разделе этой страницы, библиотеки и фреймворки Scala, подобные нижеследующим, +были написаны для поддержки загруженных веб-сайтов и работы с огромными наборами данных: + +1. [Play Framework](https://www.playframework.com) — это легкая, без сохранения состояния, удобная для web, удобная для разработчиков архитектура для создания масштабируемых приложений +2. [Lagom](https://www.lagomframework.com) — это инфраструктура микросервисов, которая помогает разделить устаревший монолит и создавать, тестировать и развертывать целые системы реактивных микросервисов +3. [Apache Spark](https://spark.apache.org) — это унифицированный аналитический механизм для обработки больших данных со встроенными модулями для потоковой передачи, SQL, машинного обучения и обработки графиков + +В [списке Awesome Scala](https://github.com/lauris/awesome-scala) представлены десятки дополнительных инструментов +с открытым исходным кодом, созданных разработчиками для создания приложений Scala. + +В дополнение к программированию на стороне сервера, [Scala.js](https://www.scala-js.org) представляет собой +строго типизированную замену для написания JavaScript со сторонними библиотеками с открытым исходным кодом, +которые включают инструменты для интеграции с библиотекой Facebook React, jQuery и т.д. + + +## Функции низкоуровневого языка + +Хотя в предыдущем разделе были рассмотрены высокоуровневые функции Scala, интересно отметить, +что на высоком уровне вы можете делать одни и те же утверждения как о Scala 2, так и о Scala 3. +Десять лет назад Scala начиналась с прочного фундамента желаемых функций, и вы увидите в этом разделе, +что в Scala 3 эти преимущества были улучшены. + +С точки зрения деталей “на уровне моря” — то есть функций языка, которые программисты используют каждый день — +Scala 3 имеет значительные преимущества по сравнению со Scala 2: + +- Возможность более лаконично создавать алгебраические типы данных (ADT) с перечислениями +- Еще более лаконичный и читаемый синтаксис: + - Синтаксис “тихой” структуры управления легче читать + - Опциональные фигурные скобки + - Меньшее количество символов в коде создает меньше визуального шума, что упрощает его чтение + - Ключевое слово `new` обычно больше не требуется при создании экземпляров класса + - Формальность объектов пакета была заменена более простыми определениями “верхнего уровня” +- Более понятная грамматика: + - Несколько различных вариантов использования ключевого слова `implicit` были удалены; это использование заменено более очевидными ключевыми словами, такими как `given`, `using`, и `extension`, фокусирующихся на намерении, а не механизме (подробности см. в разделе [Givens][givens]) + - [Методы расширения][extension] заменяют неявные классы более понятным и простым механизмом + - Добавление модификатора `open` для классов заставляет разработчика намеренно объявить, что класс открыт для модификации, тем самым ограничивая специальные расширения кодовой базы + - [Многостороннее равенство][multiversal] исключает бессмысленные сравнения с `==` и `!=` (т.е. попытки сравнить `Person` с `Planet`) + - Гораздо проще реализуются макросы + - Объединение и пересечение предлагают гибкий способ моделирования типов + - Параметры трейтов заменяют и упрощают ранние инициализаторы + - [Псевдонимы непрозрачных типов][opaque_types] заменяют большинство случаев использования классов значений, гарантируя при этом отсутствие упаковки + - Export предложения обеспечивают простой и общий способ выражения агрегации, который может заменить предыдущий шаблон фасада объектов пакета, наследуемых от классов + - Синтаксис procedure был удален, а синтаксис varargs - изменен, чтобы сделать язык более согласованным + - `@infix` аннотация делает очевидным желаемое применение метода + - Аннотация метода [`@targetName`]({{ site.scala3ref }}/other-new-features/targetName.html) определяет альтернативное имя метода, улучшая совместимость с Java и позволяя указывать псевдонимы для символических операторов + +Демонстрация всех этих функций заняла бы слишком много места, но перейдите по ссылкам в пунктах выше, чтобы увидеть эти функции в действии. +Все эти функции подробно обсуждаются на страницах *New*, *Changed* и *Dropped* функций в [обзорной документации][reference]. + + +## Экосистема Scala + + +У Scala динамичная экосистема с библиотеками и фреймворками под любые требования. +[Список “Awesome Scala”](https://github.com/lauris/awesome-scala) содержит список сотен проектов с открытым исходным кодом, +доступных разработчикам Scala, а [Scaladex](https://index.scala-lang.org) предоставляет доступный для поиска индекс библиотек Scala. +Некоторые из наиболее известных библиотек перечислены ниже. + + + +### Web разработка + +- [Play Framework](https://www.playframework.com) следует модели Ruby on Rails, чтобы стать легкой, не сохраняющей состояния, + удобной для разработчиков и web архитектурой для высокомасштабируемых приложений +- [Scalatra](https://scalatra.org) — небольшой высокопроизводительный асинхронный web framework, вдохновленный Sinatra +- [Finatra](https://twitter.github.io/finatra) — это сервисы Scala, построенные на TwitterServer и Finagle +- [Scala.js](https://www.scala-js.org) — это строго типизированная замена JavaScript, обеспечивающая более безопасный способ создания надежных интерфейсных web-приложений +- [ScalaJs-React](https://github.com/japgolly/scalajs-react) поднимает библиотеку Facebook React на Scala.js и пытается сделать ее максимально безопасной для типов и удобной для Scala +- [Lagom](https://www.lagomframework.com) — это инфраструктура микросервисов, которая помогает разделить устаревший монолит и создавать, тестировать и развертывать целые системы реактивных микросервисов + + +HTTP(S) библиотеки: - [Akka-http](https://akka.io) - [Finch](https://github.com/finagle/finch) - [Http4s](https://github.com/http4s/http4s) - [Sttp](https://github.com/softwaremill/sttp) -JSON libraries: +JSON библиотеки: - [Argonaut](https://github.com/argonaut-io/argonaut) - [Circe](https://github.com/circe/circe) - [Json4s](https://github.com/json4s/json4s) - [Play-JSON](https://github.com/playframework/play-json) -Serialization: +Сериализация: - [ScalaPB](https://github.com/scalapb/ScalaPB) -### Science and data analysis: +### Наука и анализ данных: - [Algebird](https://github.com/twitter/algebird) - [Spire](https://github.com/typelevel/spire) - [Squants](https://github.com/typelevel/squants) -### Big data +### Большие данные - [Apache Spark](https://github.com/apache/spark) - [Apache Flink](https://github.com/apache/flink) -### AI, machine learning +### ИИ, машинное обучение - [BigDL](https://github.com/intel-analytics/BigDL) (Distributed Deep Learning Framework for Apache Spark) for Apache Spark - [TensorFlow Scala](https://github.com/eaplatanios/tensorflow_scala) -### Functional Programming & Functional Reactive Programming +### Функциональное программирование & Функциональное реактивное программирование -FP: +ФП: - [Cats](https://github.com/typelevel/cats) - [Zio](https://github.com/zio/zio) -Functional reactive programming (FRP): +Функциональное реактивное программирование (ФРП): - [fs2](https://github.com/typelevel/fs2) - [monix](https://github.com/monix/monix) -### Build tools +### Инструменты сборки - [sbt](https://www.scala-sbt.org) - [Gradle](https://gradle.org) @@ -559,10 +473,10 @@ Functional reactive programming (FRP): -## Summary - -As this page shows, Scala has many terrific programming language features at a high level, at an everyday programming level, and through its developer ecosystem. +## Подведем итоги +Как показано на этой странице, Scala обладает множеством замечательных функций высокоуровневого языка программирования, +на уровне повседневного программирования и в экосистеме разработчиков. [reference]: {{ site.scala3ref }}/overview.html @@ -571,5 +485,3 @@ As this page shows, Scala has many terrific programming language features at a h [givens]: {% link _overviews/scala3-book/ca-given-using-clauses.md %} [opaque_types]: {% link _overviews/scala3-book/types-opaque-types.md %} - - From db66dabca79dd318fe7885ff47b6ca7b1d37e4e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Fri, 23 Sep 2022 09:44:20 +0300 Subject: [PATCH 09/14] Add scala 3 book in russian --- _ru/scala3/book/scala-features.md | 2 +- _ru/scala3/book/why-scala-3.md | 93 ++++++++++++++++--------------- 2 files changed, 50 insertions(+), 45 deletions(-) diff --git a/_ru/scala3/book/scala-features.md b/_ru/scala3/book/scala-features.md index d70bde8758..55fac08cc8 100644 --- a/_ru/scala3/book/scala-features.md +++ b/_ru/scala3/book/scala-features.md @@ -448,7 +448,7 @@ JSON библиотеки: ### ИИ, машинное обучение -- [BigDL](https://github.com/intel-analytics/BigDL) (Distributed Deep Learning Framework for Apache Spark) for Apache Spark +- [BigDL](https://github.com/intel-analytics/BigDL) (Распределенная среда глубокого обучения для Apache Spark) - [TensorFlow Scala](https://github.com/eaplatanios/tensorflow_scala) diff --git a/_ru/scala3/book/why-scala-3.md b/_ru/scala3/book/why-scala-3.md index f2dee5d341..490c89ae5c 100644 --- a/_ru/scala3/book/why-scala-3.md +++ b/_ru/scala3/book/why-scala-3.md @@ -15,27 +15,28 @@ next-page: taste-intro Использование Scala, и Scala 3 в частности, дает много преимуществ. Трудно перечислить их все, но “топ десять” может выглядеть так: -1. Scala embraces a fusion of functional programming (FP) and object-oriented programming (OOP) -2. Scala is statically typed, but often feels like a dynamically typed language -3. Scala’s syntax is concise, but still readable; it’s often referred to as _expressive_ -4. _Implicits_ in Scala 2 were a defining feature, and they have been improved and simplified in Scala 3 -5. Scala integrates seamlessly with Java, so you can create projects with mixed Scala and Java code, and Scala code easily uses the thousands of existing Java libraries -6. Scala can be used on the server, and also in the browser with [Scala.js](https://www.scala-js.org) -7. The Scala standard library has dozens of pre-built, functional methods to save you time, and greatly reduce the need to write custom `for` loops and algorithms -8. “Best practices” are built into Scala, which favors immutability, anonymous functions, higher-order functions, pattern matching, classes that cannot be extended by default, and more -9. The Scala ecosystem offers the most modern FP libraries in the world -10. Strong type system +1. Scala сочетает в себе функциональное программирование (ФП) и объектно-ориентированное программирование (ООП) +2. Scala статически типизирован, но часто ощущается как язык с динамической типизацией +3. Синтаксис Scala лаконичен, но все же удобочитаем; его часто называют _выразительным_ +4. _Implicits_ в Scala 2 были определяющей функцией, а в Scala 3 они были улучшены и упрощены +5. Scala легко интегрируется с Java, поэтому вы можете создавать проекты со смешанным кодом Scala и Java, а код Scala легко использует тысячи существующих библиотек Java +6. Scala можно использовать на сервере, а также в браузере со [Scala.js](https://www.scala-js.org) +7. Стандартная библиотека Scala содержит десятки готовых функциональных методов, позволяющих сэкономить ваше время и значительно сократить потребность в написании пользовательских циклов `for` и алгоритмов +8. “Best practices”, встроенные в Scala, поддерживают неизменность, анонимные функции, функции высшего порядка, сопоставление с образцом, классы, которые не могут быть расширены по умолчанию, и многое другое +9. Экосистема Scala предлагает самые современные ФП библиотеки в мире +10. Сильная система типов -## 1) FP/OOP fusion -More than any other language, Scala supports a fusion of the FP and OOP paradigms. -As Martin Odersky has stated, the essence of Scala is a fusion of functional and object-oriented programming in a typed setting, with: +## 1) Слияние ФП/ООП -- Functions for the logic, and -- Objects for the modularity +Больше, чем любой другой язык, Scala поддерживает слияние парадигм ФП и ООП. +Как заявил Мартин Одерски, сущность Scala — это слияние функционального и объектно-ориентированного программирования в типизированной среде с: -Possibly some of the best examples of modularity are the classes in the standard library. -For instance, a `List` is defined as a class---technically it’s an abstract class---and a new instance is created like this: +- Функции для логики и +- Объекты для модульности + +Возможно, одними из лучших примеров модульности являются классы стандартной библиотеки. +Например, `List` определяется как класс---технически это абстрактный класс---и новый экземпляр создается следующим образом: {% tabs list %} {% tab 'Scala 2 and 3' for=list %} @@ -45,10 +46,12 @@ val x = List(1, 2, 3) {% endtab %} {% endtabs %} -However, what appears to the programmer to be a simple `List` is actually built from a combination of several specialized types, including traits named `Iterable`, `Seq`, and `LinearSeq`. -Those types are similarly composed of other small, modular units of code. +Однако то, что кажется программисту простым `List`, на самом деле построено из комбинации нескольких специализированных типов, +включая трейты с именами `Iterable`, `Seq` и `LinearSeq`. +Эти типы также состоят из других небольших модульных единиц кода. -In addition to building a type like `List` from a series of modular traits, the `List` API also consists of dozens of other methods, many of which are higher-order functions: +В дополнение к построению типа наподобие `List` из серии модульных трейтов, +`List` API также состоит из десятков других методов, многие из которых являются функциями высшего порядка: {% tabs list-methods %} {% tab 'Scala 2 and 3' for=list-methods %} @@ -63,13 +66,13 @@ xs.takeWhile(_ < 3) // List(1, 2) {% endtab %} {% endtabs %} -In those examples, the values in the list can’t be modified. -The `List` class is immutable, so all of those methods return new values, as shown by the data in each comment. +В этих примерах значения в списке не могут быть изменены. +Класс `List` неизменяем, поэтому все эти методы возвращают новые значения, как показано в каждом комментарии. -## 2) A dynamic feel +## 2) Ощущение динамики -Scala’s _type inference_ often makes the language feel dynamically typed, even though it’s statically typed. -This is true with variable declaration: +_Вывод типов_ (_type inference_) в Scala часто заставляет язык чувствовать себя динамически типизированным, даже если он статически типизирован. +Это верно для объявления переменной: {% tabs dynamic %} {% tab 'Scala 2 and 3' for=dynamic %} @@ -82,7 +85,7 @@ val stuff = ("fish", 42, 1_234.5) {% endtab %} {% endtabs %} -It’s also true when passing anonymous functions to higher-order functions: +Это также верно при передаче анонимных функций функциям высшего порядка: {% tabs dynamic-hof %} {% tab 'Scala 2 and 3' for=dynamic-hof %} @@ -95,7 +98,7 @@ list.filter(_ < 4) {% endtab %} {% endtabs %} -and when defining methods: +и при определении методов: {% tabs dynamic-method %} {% tab 'Scala 2 and 3' for=dynamic-method %} @@ -105,27 +108,27 @@ def add(a: Int, b: Int) = a + b {% endtab %} {% endtabs %} -This is more true than ever in Scala 3, such as when using [union types][union-types]: +Это как никогда верно для Scala 3, например, при использовании [типов объединения][union-types]: {% tabs union %} {% tab 'Scala 3 Only' for=union %} ```scala -// union type parameter +// параметр типа объединения def help(id: Username | Password) = val user = id match case Username(name) => lookupName(name) case Password(hash) => lookupPassword(hash) - // more code here ... + // дальнейший код ... -// union type value +// значение типа объединения val b: Password | Username = if (true) name else password ``` {% endtab %} {% endtabs %} -## 3) Concise syntax +## 3) Лаконичный синтаксис -Scala is a low ceremony, “concise but still readable” language. For instance, variable declaration is concise: +Scala — это неформальный, “краткий, но все же читабельный“ язык. Например, объявление переменной лаконично: {% tabs concise %} {% tab 'Scala 2 and 3' for=concise %} @@ -137,7 +140,7 @@ val c = List(1,2,3) {% endtab %} {% endtabs %} -Creating types like traits, classes, and enumerations are concise: +Создание типов, таких как трейты, классы и перечисления, является кратким: {% tabs enum %} {% tab 'Scala 3 Only' for=enum %} @@ -160,7 +163,7 @@ case class Person( {% endtab %} {% endtabs %} -Higher-order functions are concise: +Функции высшего порядка кратки: {% tabs list-hof %} {% tab 'Scala 2 and 3' for=list-hof %} @@ -172,19 +175,21 @@ list.map(_ * 2) {% endtab %} {% endtabs %} -All of these expressions and many more are concise, and still very readable: what we call _expressive_. +Все эти и многие другие выражения кратки и при этом очень удобочитаемы: то, что мы называем _выразительным_ (_expressive_). -## 4) Implicits, simplified +## 4) Implicits, упрощение -Implicits in Scala 2 were a major distinguishing design feature. -They represented _the_ fundamental way to abstract over context, with a unified paradigm that served a great variety of use cases, among them: +Implicits в Scala 2 были главной отличительной особенностью дизайна. +Они представляли собой фундаментальный способ абстрагирования от контекста с единой парадигмой, +которая обслуживала множество вариантов использования, среди которых: -- Implementing [type classes]({% link _overviews/scala3-book/ca-type-classes.md %}) -- Establishing context -- Dependency injection -- Expressing capabilities +- Реализация [типовых классов]({% link _overviews/scala3-book/ca-type-classes.md %}) +- Установление контекста +- Внедрение зависимости +- Выражение возможностей -Since then, other languages have adopted similar concepts, all of which are variants of the core idea of _term inference_: Given a type, the compiler synthesizes a “canonical” term that has that type. +С тех пор другие языки приняли аналогичные концепции, все из которых являются вариантами основной идеи вывода терминов: +при заданном типе компилятор синтезирует “канонический” термин, имеющий этот тип. While implicits were a defining feature in Scala 2, their design has been greatly improved in Scala 3: From 3dc95268205269d383bb7c9a172200a3ff01c751 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Fri, 23 Sep 2022 19:48:52 +0300 Subject: [PATCH 10/14] Add scala 3 book in russian --- _ru/scala3/book/why-scala-3.md | 258 ++++++++++++++++----------------- 1 file changed, 122 insertions(+), 136 deletions(-) diff --git a/_ru/scala3/book/why-scala-3.md b/_ru/scala3/book/why-scala-3.md index 490c89ae5c..bb5b0b55a1 100644 --- a/_ru/scala3/book/why-scala-3.md +++ b/_ru/scala3/book/why-scala-3.md @@ -181,76 +181,85 @@ list.map(_ * 2) Implicits в Scala 2 были главной отличительной особенностью дизайна. Они представляли собой фундаментальный способ абстрагирования от контекста с единой парадигмой, -которая обслуживала множество вариантов использования, среди которых: +обслуживающей множество вариантов использования, среди которых: - Реализация [типовых классов]({% link _overviews/scala3-book/ca-type-classes.md %}) - Установление контекста - Внедрение зависимости - Выражение возможностей -С тех пор другие языки приняли аналогичные концепции, все из которых являются вариантами основной идеи вывода терминов: -при заданном типе компилятор синтезирует “канонический” термин, имеющий этот тип. +С тех пор другие языки внедрили аналогичные концепции, все из которых являются вариантами основной идеи _вывода терминов_: +при заданном типе компилятор синтезирует “канонический” термин этого типа. -While implicits were a defining feature in Scala 2, their design has been greatly improved in Scala 3: +Хотя implicits были определяющей функцией в Scala 2, их дизайн был значительно улучшен в Scala 3: -- There’s a single way to define “given” values -- There’s a single way to introduce implicit parameters and arguments -- There’s a separate way to import givens that does not allow them to hide in a sea of normal imports -- There’s a single way to define an implicit conversion, which is clearly marked as such, and does not require special syntax +- Есть единственный способ определить значения “given” +- Есть единственный способ ввести неявные параметры и аргументы +- Есть отдельный способ импорта givens, который не позволяет им потеряться в море обычного импорта +- Существует единственный способ определить неявное преобразование, которое четко обозначено как таковое и не требует специального синтаксиса -Benefits of these changes include: +К преимуществам этих изменений относятся: -- The new design avoids feature interactions and makes the language more consistent -- It makes implicits easier to learn and harder to abuse -- It greatly improves the clarity of the 95% of Scala programs that use implicits -- It has the potential to enable term inference in a principled way that’s also accessible and friendly +- Новый дизайн позволяет избежать взаимодействия функциональностей и делает язык более согласованным +- Это делает implicits более простыми для изучения и более сложными для злоупотребления +- Это значительно улучшает ясность 95% программ Scala, использующих implicits +- У него есть потенциал, чтобы сделать вывод терминов принципиальным способом, который также доступен и удобен -These capabilities are described in detail in other sections, so see the [Contextual Abstraction introduction][contextual], and the section on [`given` and `using` clauses][given] for more details. +Эти возможности подробно расписаны в соответствующих разделах, таких как [введение в контекстную абстракцию][contextual], а также раздел о [`given` и предложениях `using`][given] для получения более подробной информации. -## 5) Seamless Java integration +## 5) Полная интеграция с Java -Scala/Java interaction is seamless in many ways. -For instance: +Взаимодействие между Scala и Java не вызывает затруднений во многих ситуациях. +Например: -- You can use all of the thousands of Java libraries that are available in your Scala projects -- A Scala `String` is essentially a Java `String`, with additional capabilities added to it -- Scala seamlessly uses the date/time classes in the Java *java.time._* package +- Вы можете использовать все тысячи библиотек Java, доступных в ваших проектах Scala +- Scala `String` — это, по сути Java `String`, с дополнительными возможностями +- Scala легко использует классы даты/времени из Java пакета *java.time._* -You can also use Java collections classes in Scala, and to give them more functionality, Scala includes methods so you can transform them into Scala collections. +Вы также можете использовать классы коллекций Java в Scala, а для придания им большей функциональности Scala включает методы, +позволяющие преобразовывать их в коллекции Scala. -While almost every interaction is seamless, the [“Interacting with Java” chapter][java] demonstrates how to use some features together better, including how to use: +Несмотря на то, что почти каждое взаимодействие является бесшовным, +в [главе “Взаимодействие с Java”][java] показано, как лучше использовать некоторые функции вместе, +в том числе как использовать: -- Java collections in Scala -- Java `Optional` in Scala -- Java interfaces in Scala -- Scala collections in Java -- Scala `Option` in Java -- Scala traits in Java -- Scala methods that throw exceptions in Java code -- Scala varargs parameters in Java +- Коллекции Java в Scala +- Java `Optional` в Scala +- Интерфейсы Java в Scala +- Коллекции Scala в Java +- Scala `Option` в Java +- Scala traits в Java +- Методы Scala, вызывающие исключения в Java коде +- Scala varargs параметры в Java -See that chapter for more details on these features. +Подробнее об этих функциях см. в этой главе. -## 6) Client & server +## 6) Клиент & сервер -Scala can be used on the server side with terrific frameworks: +Scala можно использовать на стороне сервера с потрясающими фреймворками: -- The [Play Framework](https://www.playframework.com) lets you build highly scalable server-side applications and microservices -- [Akka Actors](https://akka.io) let you use the actor model to greatly simplify distributed and concurrent software applications +- [Play Framework](https://www.playframework.com) позволяет создавать масштабируемые серверные приложения и микросервисы +- [Akka Actors](https://akka.io) позволяет использовать модель акторов для значительного упрощения распределенных и параллельных программных приложений -Scala can also be used in the browser with the [Scala.js project](https://www.scala-js.org), which is a type-safe replacement for JavaScript. -The Scala.js ecosystem [has dozens of libraries](https://www.scala-js.org/libraries) to let you use React, Angular, jQuery, and many other JavaScript and Scala libraries in the browser. +Scala также можно использовать в браузере с [проектом Scala.js](https://www.scala-js.org), который является безопасной заменой JavaScript. +В экосистеме Scala.js есть [десятки библиотек](https://www.scala-js.org/libraries), позволяющих использовать React, Angular, jQuery +и многие другие библиотеки JavaScript и Scala в браузере. -In addition to those tools, the [Scala Native](https://github.com/scala-native/scala-native) project “is an optimizing ahead-of-time compiler and lightweight managed runtime designed specifically for Scala.” It lets you build “systems” style binary executable applications with plain Scala code, and also lets you use lower-level primitives. +В дополнение к этим инструментам проект [Scala Native](https://github.com/scala-native/scala-native) +“представляет собой оптимизирующий опережающий компилятор и облегченную управляемую среду выполнения, разработанную специально для Scala”. +Он позволяет создавать бинарные исполняемые приложения в “системном” стиле с помощью простого кода Scala, а также позволяет использовать низкоуровневые примитивы. -## 7) Standard library methods +## 7) Стандартные библиотечные методы -You will rarely ever need to write a custom `for` loop again, because the dozens of pre-built functional methods in the Scala standard library will both save you time, and help make code more consistent across different applications. +Вам довольно редко понадобится писать пользовательский цикл `for`, +потому что десятки готовых функциональных методов в стандартной библиотеке Scala сэкономят ваше время +и помогут сделать код более согласованным в разных приложениях. -The following examples show some of the built-in collections methods, and there are many in addition to these. -While these all use the `List` class, the same methods work with other collections classes like `Seq`, `Vector`, `LazyList`, `Set`, `Map`, `Array`, and `ArrayBuffer`. +В следующих примерах показаны некоторые из встроенных методов коллекций, а также многие другие. +Хотя все они используют класс `List`, одни и те же методы работают с другими классами коллекций, +такими как `Seq`, `Vector`, `LazyList`, `Set`, `Map`, `Array` и `ArrayBuffer`. -Here are some examples: +Вот некоторые примеры: {% tabs list-more %} {% tab 'Scala 2 and 3' for=list-more %} @@ -295,31 +304,31 @@ nums.sortWith(_ > _) // List(10, 8, 7, 5, 1) {% endtab %} {% endtabs %} -## 8) Built-in best practices +## 8) Встроенные "best practices" -Scala idioms encourage best practices in many ways. -For immutability, you’re encouraged to create immutable `val` declarations: +Идиомы Scala поощряют лучшие практики во многих ситуациях. +Для неизменяемости рекомендуется создавать неизменяемые val декларации: {% tabs val %} {% tab 'Scala 2 and 3' for=val %} ```scala -val a = 1 // immutable variable +val a = 1 // неизменяемая переменная ``` {% endtab %} {% endtabs %} -You’re also encouraged to use immutable collections classes like `List` and `Map`: +Вам также рекомендуется использовать неизменяемые классы коллекций, такие как `List` и `Map`: {% tabs list-map %} {% tab 'Scala 2 and 3' for=list-map %} ```scala -val b = List(1,2,3) // List is immutable -val c = Map(1 -> "one") // Map is immutable +val b = List(1,2,3) // List неизменяем +val c = Map(1 -> "one") // Map неизменяема ``` {% endtab %} {% endtabs %} -Case classes are primarily intended for use in [domain modeling]({% link _overviews/scala3-book/domain-modeling-intro.md %}), and their parameters are immutable: +Case классы в первую очередь предназначены для использования в [моделировании предметной области]({% link _overviews/scala3-book/domain-modeling-intro.md %}), и их параметры неизменяемы: {% tabs case-class %} {% tab 'Scala 2 and 3' for=case-class %} @@ -327,12 +336,13 @@ Case classes are primarily intended for use in [domain modeling]({% link _overvi case class Person(name: String) val p = Person("Michael Scott") p.name // Michael Scott -p.name = "Joe" // compiler error (reassignment to val name) +p.name = "Joe" // compiler error (переназначение val name) ``` {% endtab %} {% endtabs %} -As shown in the previous section, Scala collections classes support higher-order functions, and you can pass methods (not shown) and anonymous functions into them: +Как показано в предыдущем разделе, классы коллекций Scala поддерживают функции высшего порядка, +и вы можете передавать в них методы (не показаны) и анонимные функции: {% tabs higher-order %} {% tab 'Scala 2 and 3' for=higher-order %} @@ -347,7 +357,7 @@ nums.sortWith(_ > _) {% endtab %} {% endtabs %} -`match` expressions let you use pattern matching, and they truly are _expressions_ that return values: +Выражения `match` позволяют использовать сопоставление с образцом, и они действительно являются _выражениями_, которые возвращают значения: {% tabs match class=tabs-scala-version %} {% tab 'Scala 2' for=match %} @@ -370,7 +380,7 @@ val numAsString = i match {% endtab %} {% endtabs %} -Because they can return values, they’re often used as the body of a method: +Поскольку они могут возвращать значения, их часто используют в качестве тела метода: {% tabs match-body class=tabs-scala-version %} {% tab 'Scala 2' for=match-body %} @@ -391,80 +401,55 @@ def isTruthy(a: Matchable) = a match {% endtab %} {% endtabs %} -## 9) Ecosystem libraries - -Scala libraries for functional programming like [Cats](https://typelevel.org/cats) and [Zio](https://zio.dev) are leading-edge libraries in the FP community. -All of the buzzwords like high-performance, type safe, concurrent, asynchronous, resource-safe, testable, functional, modular, binary-compatible, efficient, effects/effectful, and more, can be said about these libraries. - -We could list hundreds of libraries here, but fortunately they’re all listed in another location: For those details, see the [“Awesome Scala” list](https://github.com/lauris/awesome-scala). - -## 10) Strong type system - -Scala has a strong type system, and it’s been improved even more in Scala 3. -Scala 3’s goals were defined early on, and those related to the type system include: - -- Simplification -- Eliminate inconsistencies -- Safety -- Ergonomics -- Performance - -_Simplification_ comes about through dozens of changed and dropped features. -For instance, the changes from the overloaded `implicit` keyword in Scala 2 to the terms `given` and `using` in Scala 3 make the language more clear, especially for beginning developers. - -_Eliminating inconsistencies_ is related to the dozens of [dropped features][dropped], [changed features][changed], and [added features][added] in Scala 3. -Some of the most important features in this category are: - -- Intersection types -- Union types -- Implicit function types -- Dependent function types -- Trait parameters -- Generic tuples - -{% comment %} -A list of types from the Dotty documentation: - -- Inferred types -- Generics -- Intersection types -- Union types -- Structural types -- Dependent function types -- Type classes -- Opaque types -- Variance -- Algebraic Data Types -- Wildcard arguments in types: ? replacing _ -- Type lambdas -- Match types -- Existential types -- Higher-kinded types -- Singleton types -- Refinement types -- Kind polymorphism -- Abstract type members and path-dependent types -- Dependent function types -- Bounds -{% endcomment %} - -_Safety_ is related to several new and changed features: - -- Multiversal equality -- Restricting implicit conversions -- Null safety -- Safe initialization - -Good examples of _ergonomics_ are enumerations and extension methods, which have been added to Scala 3 in a very readable manner: +## 9) Библиотеки экосистемы + +Библиотеки Scala для функционального программирования, такие как [Cats](https://typelevel.org/cats) и [Zio](https://zio.dev), +являются передовыми библиотеками в сообществе ФП. +Об этих библиотеках можно сказать все модные словечки, такие как высокопроизводительная, типобезопасная, параллельная, асинхронная, ресурсобезопасная, тестируемая, функциональная, модульная, бинарно-совместимая, эффективная, эффектная и т.д. + +Мы могли бы перечислить здесь сотни библиотек, но, к счастью, все они перечислены в другом месте: подробности см. в списке [“Awesome Scala”](https://github.com/lauris/awesome-scala). + +## 10) Сильная система типов + +В Scala есть сильная система типов, и она была еще больше улучшена в Scala 3. +Цели Scala 3 были определены на раннем этапе, и к ним относятся: + +- Упрощение +- Устранение несоответствий +- Безопасность +- Эргономика +- Производительность + +_Упрощение_ достигается за счет десятков измененных и удаленных функций. +Например, изменения перегруженного ключевого слова `implicit` в Scala 2 на термины `given` и `using` в Scala 3 делает язык более понятным, особенно для начинающих разработчиков. + +_Устранение несоответствий_ связано с десятками [удаленных функций][dropped], [измененных функций][changed], и [добавленных функций][added] в Scala 3. +Некоторые из наиболее важных функций в этой категории: + +- Типы пересечения +- Типы объединения +- Неявные функциональные типы +- Зависимые функциональные типы +- Параметры трейтов +- Generic кортежи + +_Безопасность_ связана с несколькими новыми и измененными функциями: + +- Мультиверсальное равенство +- Ограничение неявных преобразований +- Null безопасность +- Безопасная инициализация + +Хорошими примерами _эргономики_ являются перечисления и методы расширения, которые были добавлены в Scala 3 очень удобочитаемым образом: {% tabs extension %} {% tab 'Scala 3 Only' for=extension %} ```scala -// enumeration +// перечисления enum Color: case Red, Green, Blue -// extension methods +// методы расширения extension (c: Circle) def circumference: Double = c.radius * math.Pi * 2 def diameter: Double = c.radius * 2 @@ -473,25 +458,26 @@ extension (c: Circle) {% endtab %} {% endtabs %} -_Performance_ relates to several areas. -One of those is [opaque types][opaque-types]. -In Scala 2 there were several attempts to create solutions to keep with the Domain-driven design (DDD) practice of giving values more meaningful types. -These attempts included: +_Производительность_ относится к нескольким областям. +Одним из них являются [непрозрачные типы][opaque-types]. +В Scala 2 было несколько попыток создать решения, соответствующие практике проектирования, управляемого предметной областью (DDD), +когда значениям присваивались более осмысленные типы. +Эти попытки включали: -- Type aliases -- Value classes -- Case classes +- Псевдонимы типов +- Классы значений +- Case классы -Unfortunately all of these approaches had weaknesses, as described in the [_Opaque Types_ SIP](https://docs.scala-lang.org/sips/opaque-types.html). -Conversely, the goal of opaque types, as described in that SIP, is that “operations on these wrapper types must not create any extra overhead at runtime while still providing a type safe use at compile time.” +К сожалению, у всех этих подходов были недостатки, как описано в [SIP непрозрачных типов](https://docs.scala-lang.org/sips/opaque-types.html). +И наоборот, цель непрозрачных типов, как описано в этом SIP, заключается в том, что “операции с этими типами-оболочками не должны создавать дополнительных накладных расходов во время выполнения, но при этом обеспечивать безопасное использование типов во время компиляции”. -For more type system details, see the [Reference documentation][reference]. +Дополнительные сведения о системе типов см. в [справочной документации][reference]. -## Other great features +## Другие замечательные функции -Scala has many great features, and choosing a Top 10 list can be subjective. -Several surveys have shown that different groups of developers love different features. -Hopefully you’ll discover more great Scala features as you use the language. +Scala обладает множеством замечательных функций, и выбор Топ-10 может быть субъективным. +Несколько опросов показали, что разные группы разработчиков любят разные функции. +Надеемся, вы откроете для себя больше замечательных возможностей Scala по мере использования языка. [java]: {% link _overviews/scala3-book/interacting-with-java.md %} [given]: {% link _overviews/scala3-book/ca-given-using-clauses.md %} From 4051ce841322bb60a76dd7ac1ecf4aa3612acf86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Fri, 23 Sep 2022 20:09:11 +0300 Subject: [PATCH 11/14] Add scala 3 book in russian --- _ru/scala3/book/why-scala-3.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/_ru/scala3/book/why-scala-3.md b/_ru/scala3/book/why-scala-3.md index bb5b0b55a1..635af4718d 100644 --- a/_ru/scala3/book/why-scala-3.md +++ b/_ru/scala3/book/why-scala-3.md @@ -213,7 +213,7 @@ Implicits в Scala 2 были главной отличительной особ Например: - Вы можете использовать все тысячи библиотек Java, доступных в ваших проектах Scala -- Scala `String` — это, по сути Java `String`, с дополнительными возможностями +- Scala `String` — это, по сути, Java `String` с дополнительными возможностями - Scala легко использует классы даты/времени из Java пакета *java.time._* Вы также можете использовать классы коллекций Java в Scala, а для придания им большей функциональности Scala включает методы, @@ -307,7 +307,7 @@ nums.sortWith(_ > _) // List(10, 8, 7, 5, 1) ## 8) Встроенные "best practices" Идиомы Scala поощряют лучшие практики во многих ситуациях. -Для неизменяемости рекомендуется создавать неизменяемые val декларации: +Для неизменяемости рекомендуется создавать неизменяемые val переменные: {% tabs val %} {% tab 'Scala 2 and 3' for=val %} @@ -440,7 +440,8 @@ _Безопасность_ связана с несколькими новыми - Null безопасность - Безопасная инициализация -Хорошими примерами _эргономики_ являются перечисления и методы расширения, которые были добавлены в Scala 3 очень удобочитаемым образом: +Хорошими примерами _эргономики_ являются перечисления и методы расширения, +добавленные в Scala 3 довольно удобочитаемым образом: {% tabs extension %} {% tab 'Scala 3 Only' for=extension %} @@ -476,7 +477,7 @@ _Производительность_ относится к нескольки ## Другие замечательные функции Scala обладает множеством замечательных функций, и выбор Топ-10 может быть субъективным. -Несколько опросов показали, что разные группы разработчиков любят разные функции. +Несколько опросов показали, что разные группы разработчиков ценят разные функции. Надеемся, вы откроете для себя больше замечательных возможностей Scala по мере использования языка. [java]: {% link _overviews/scala3-book/interacting-with-java.md %} From 9cd040c145818d5790fa4ca72874d9e73fad8e9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Sat, 24 Sep 2022 09:26:34 +0300 Subject: [PATCH 12/14] Add scala 3 book in russian --- _ru/scala3/book/taste-hello-world.md | 76 +++++++++++++++------------- _ru/scala3/book/taste-intro.md | 15 +++--- 2 files changed, 48 insertions(+), 43 deletions(-) diff --git a/_ru/scala3/book/taste-hello-world.md b/_ru/scala3/book/taste-hello-world.md index da4b2d4c89..1a029de9ef 100644 --- a/_ru/scala3/book/taste-hello-world.md +++ b/_ru/scala3/book/taste-hello-world.md @@ -12,15 +12,14 @@ previous-page: taste-intro next-page: --- -> **Hint**: in the following examples try picking your preferred Scala version. +> **Подсказка**: в следующих примерах попробуйте выбрать предпочтительную для вас версию Scala. > -## Your First Scala Program +## Ваша первая Scala-программа -A Scala “Hello, World!” example goes as follows. -First, put this code in a file named _hello.scala_: - +Пример “Hello, World!” на Scala выглядит следующим образом. +Сначала поместите этот код в файл с именем _hello.scala_: {% tabs hello-world-demo class=tabs-scala-version %} @@ -33,9 +32,10 @@ object hello { } } ``` -> In this code, we defined a method named `main`, inside a Scala `object` named `hello`. -> An `object` in Scala is similar to a `class`, but defines a singleton instance that you can pass around. -> `main` takes an input parameter named `args` that must be typed as `Array[String]`, (ignore `args` for now). +> В этом коде мы определили метод с именем `main` внутри Scala `object`-а с именем `hello`. +> `object` в Scala похож на `class`, но определяет экземпляр singleton, который можно передать. +> `main` принимает входной параметр с именем `args`, который должен иметь тип `Array[String]` +> (`args` пока можно игнорировать). {% endtab %} @@ -43,22 +43,22 @@ object hello { ```scala @main def hello() = println("Hello, World!") ``` -> In this code, `hello` is a method. -> It’s defined with `def`, and declared to be a “main” method with the `@main` annotation. -> It prints the `"Hello, World!"` string to standard output (STDOUT) using the `println` method. +> В этом коде `hello` - это метод. +> Он определяется с помощью `def` и объявляется в качестве основного метода с помощью аннотации `@main`. +> Он выводит строку "Hello, World!" на стандартный вывод (STDOUT) с помощью метода `println`. {% endtab %} {% endtabs %} -Next, compile the code with `scalac`: +Затем скомпилируйте код с помощью `scalac`: ```bash $ scalac hello.scala ``` -If you’re coming to Scala from Java, `scalac` is just like `javac`, so that command creates several files: +Если вы переходите на Scala с Java: `scalac` похоже на `javac`, эта команда создает несколько файлов: {% tabs hello-world-outputs class=tabs-scala-version %} @@ -87,25 +87,26 @@ hello.tasty {% endtabs %} -Like Java, the _.class_ files are bytecode files, and they’re ready to run in the JVM. +Как и Java, файлы _.class_ представляют собой файлы байт-кода, и они готовы к запуску в JVM. -Now you can run the `hello` method with the `scala` command: +Теперь вы можете запустить метод `hello` командой `scala`: ```bash $ scala hello Hello, World! ``` -Assuming that worked, congratulations, you just compiled and ran your first Scala application. +Если запуск прошел успешно, поздравляем, вы только что скомпилировали и запустили свое первое приложение Scala. -> More information about sbt and other tools that make Scala development easier can be found in the [Scala Tools][scala_tools] chapter. +> Дополнительную информацию о sbt и других инструментах, упрощающих разработку на Scala, можно найти в главе [Инструменты Scala][scala_tools]. -## Ask For User Input +## Запрос пользовательского ввода -In our next example let's ask for the user's name before we greet them! +В нашем следующем примере давайте спросим имя пользователя, прежде чем приветствовать его! -There are several ways to read input from a command-line, but a simple way is to use the -`readLine` method in the _scala.io.StdIn_ object. To use it, you need to first import it, like this: +Есть несколько способов прочитать ввод из командной строки, но самый простой способ — +использовать метод `readLine` из объекта _scala.io.StdIn_. +Чтобы использовать этот метод, вам нужно сначала его импортировать, например: {% tabs import-readline %} {% tab 'Scala 2 and 3' for=import-readline %} @@ -115,7 +116,8 @@ import scala.io.StdIn.readLine {% endtab %} {% endtabs %} -To demonstrate how this works, let’s create a little example. Put this source code in a file named _helloInteractive.scala_: +Чтобы продемонстрировать, как это работает, давайте создадим небольшой пример. +Поместите этот исходный код в файл с именем _helloInteractive.scala_: {% tabs hello-world-interactive class=tabs-scala-version %} @@ -152,18 +154,20 @@ import scala.io.StdIn.readLine {% endtabs %} -In this code we save the result of `readLine` to a variable called `name`, we then -use the `+` operator on strings to join `"Hello, "` with `name` and `"!"`, making one single string value. +В этом коде мы сохраняем результат из `readLine` в переменную с именем `name`, +затем используем оператор над строками `+` для соединения `"Hello, "` с `name` и `"!"`, создавая одно единственное строковое значение. -> You can learn more about using `val` by reading [Variables and Data Types](/scala3/book/taste-vars-data-types.html). +> Вы можете узнать больше об использовании val, прочитав главу [Переменные и типы данных](/scala3/book/taste-vars-data-types.html). -Then compile the code with `scalac`: +Затем скомпилируйте код с помощью `scalac`: ```bash $ scalac helloInteractive.scala ``` -Then run it with `scala helloInteractive`, this time the program will pause after asking for your name, -and wait until you type a name and press return on the keyboard, looking like this: + +Затем запустите его с помощью `scala helloInteractive`. На этот раз программа сделает паузу после запроса вашего имени +и подождет, пока вы не наберете имя и не нажмете клавишу возврата на клавиатуре. +Выглядит это так: ```bash $ scala helloInteractive @@ -171,7 +175,7 @@ Please enter your name: ▌ ``` -When you enter your name at the prompt, the final interaction should look like this: +Когда вы вводите свое имя в "приглашении", окончательное взаимодействие должно выглядеть так: ```bash $ scala helloInteractive @@ -180,10 +184,10 @@ Alvin Alexander Hello, Alvin Alexander! ``` -### A Note about Imports +### Примечание об импорте -As you saw in this application, sometimes certain methods, or other kinds of definitions that we'll see later, -are not available unless you use an `import` clause like so: +Как вы ранее видели, иногда определенные методы или другие типы определений, которые мы увидим позже, недоступны, +если вы не используете подобное предложение `import`: {% tabs import-readline-2 %} {% tab 'Scala 2 and 3' for=import-readline-2 %} @@ -193,9 +197,9 @@ import scala.io.StdIn.readLine {% endtab %} {% endtabs %} -Imports help you write code in a few ways: - - you can put code in multiple files, to help avoid clutter, and to help navigate large projects. - - you can use a code library, perhaps written by someone else, that has useful functionality - - you can know where a certain definition comes from (especially if it was not written in the current file). +Импорт помогает писать и распределять код несколькими способами: + - вы можете поместить код в несколько файлов, чтобы избежать беспорядка и облегчить навигацию в больших проектах. + - вы можете использовать библиотеку кода, возможно, написанную кем-то другим, которая имеет полезную функциональность. + - вы видите, откуда берется определенное определение (особенно если оно не было записано в текущем файле). [scala_tools]: {% link _overviews/scala3-book/scala-tools.md %} diff --git a/_ru/scala3/book/taste-intro.md b/_ru/scala3/book/taste-intro.md index cfb40c2c05..16b484daa8 100644 --- a/_ru/scala3/book/taste-intro.md +++ b/_ru/scala3/book/taste-intro.md @@ -14,16 +14,17 @@ next-page: taste-hello-world В этой главе представлен краткий обзор основных возможностей языка программирования Scala 3. -After this initial tour, the rest of the book provides more details on these features, and the [Reference documentation][reference] provides _many_ more details. +После начального ознакомления остальная часть книги содержит более подробную информацию об описанных функциях, +а [справочная документация][reference] содержит массу подробностей. -## Setting Up Scala +## Настройка Скала -Througout this chapter, and the rest of the book, we encourage you to try out the examples by either copying -them or typing them out manually. The tools necessary to follow along with the examples on your own computer -can be installed by following our [getting started guide][get-started]. +На протяжении этой главы и остальной части книги мы рекомендуем вам пробовать примеры, скопировав их или набрав вручную. +Инструменты, необходимые для работы с примерами на вашем компьютере, можно установить, +следуя нашему [руководству для началы работы со Scala][get-started]. -> Alternatively you can run the examples in a web browser with [Scastie](https://scastie.scala-lang.org), a -> fully online editor and code-runner for Scala. +> В качестве альтернативы вы можете запустить примеры в веб-браузере с помощью [Scastie](https://scastie.scala-lang.org), +> полного онлайн-редактора и исполнителя кода для Scala. [reference]: {{ site.scala3ref }}/overview.html From 90b2ea7a7ce37edafb57c9a0cdaf45124363e96a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Sat, 24 Sep 2022 09:58:59 +0300 Subject: [PATCH 13/14] Add scala 3 book in russian --- _ru/scala3/book/scala-features.md | 2 +- _ru/scala3/book/why-scala-3.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/_ru/scala3/book/scala-features.md b/_ru/scala3/book/scala-features.md index 55fac08cc8..f1eab830aa 100644 --- a/_ru/scala3/book/scala-features.md +++ b/_ru/scala3/book/scala-features.md @@ -476,7 +476,7 @@ JSON библиотеки: ## Подведем итоги Как показано на этой странице, Scala обладает множеством замечательных функций высокоуровневого языка программирования, -на уровне повседневного программирования и в экосистеме разработчиков. +низкоуровневого языка программирования и богатой экосистемой разработчиков. [reference]: {{ site.scala3ref }}/overview.html diff --git a/_ru/scala3/book/why-scala-3.md b/_ru/scala3/book/why-scala-3.md index 635af4718d..3a8efd51f3 100644 --- a/_ru/scala3/book/why-scala-3.md +++ b/_ru/scala3/book/why-scala-3.md @@ -30,9 +30,9 @@ next-page: taste-intro ## 1) Слияние ФП/ООП Больше, чем любой другой язык, Scala поддерживает слияние парадигм ФП и ООП. -Как заявил Мартин Одерски, сущность Scala — это слияние функционального и объектно-ориентированного программирования в типизированной среде с: +Как заявил Мартин Одерски, сущность Scala — это слияние функционального и объектно-ориентированного программирования в типизированной среде, где: -- Функции для логики и +- Функции для логики - Объекты для модульности Возможно, одними из лучших примеров модульности являются классы стандартной библиотеки. @@ -306,7 +306,7 @@ nums.sortWith(_ > _) // List(10, 8, 7, 5, 1) ## 8) Встроенные "best practices" -Идиомы Scala поощряют лучшие практики во многих ситуациях. +Идиомы Scala поощряют "best practices" во многих ситуациях. Для неизменяемости рекомендуется создавать неизменяемые val переменные: {% tabs val %} @@ -328,7 +328,7 @@ val c = Map(1 -> "one") // Map неизменяема {% endtab %} {% endtabs %} -Case классы в первую очередь предназначены для использования в [моделировании предметной области]({% link _overviews/scala3-book/domain-modeling-intro.md %}), и их параметры неизменяемы: +Case классы в первую очередь предназначены для использования в [моделировании предметной области]({% link _overviews/scala3-book/domain-modeling-intro.md %}), и их параметры также неизменяемы: {% tabs case-class %} {% tab 'Scala 2 and 3' for=case-class %} From a222960009fe7d46b3e78231f0364ebce15b8240 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Sun, 16 Oct 2022 09:25:04 +0300 Subject: [PATCH 14/14] Merge master and merge `languages` parameter --- _overviews/scala3-book/introduction.md | 3 +-- _overviews/scala3-book/scala-features.md | 3 +-- _overviews/scala3-book/taste-hello-world.md | 3 +-- _overviews/scala3-book/taste-intro.md | 3 +-- _overviews/scala3-book/why-scala-3.md | 3 +-- 5 files changed, 5 insertions(+), 10 deletions(-) diff --git a/_overviews/scala3-book/introduction.md b/_overviews/scala3-book/introduction.md index cbc807ac45..c1dd65583c 100644 --- a/_overviews/scala3-book/introduction.md +++ b/_overviews/scala3-book/introduction.md @@ -2,11 +2,10 @@ title: Introduction type: chapter description: This page begins the overview documentation of the Scala 3 language. -languages: [zh-cn] +languages: [ru, zh-cn] num: 1 previous-page: next-page: scala-features -languages: [ru] --- Welcome to the Scala 3 Book. diff --git a/_overviews/scala3-book/scala-features.md b/_overviews/scala3-book/scala-features.md index fa868a06d1..0e5b94f0db 100644 --- a/_overviews/scala3-book/scala-features.md +++ b/_overviews/scala3-book/scala-features.md @@ -2,11 +2,10 @@ title: Scala Features type: chapter description: This page discusses the main features of the Scala programming language. -languages: [zh-cn] +languages: [ru, zh-cn] num: 2 previous-page: introduction next-page: why-scala-3 -languages: [ru] --- diff --git a/_overviews/scala3-book/taste-hello-world.md b/_overviews/scala3-book/taste-hello-world.md index f021ca67f6..e60f2ee7be 100644 --- a/_overviews/scala3-book/taste-hello-world.md +++ b/_overviews/scala3-book/taste-hello-world.md @@ -2,11 +2,10 @@ title: Hello, World! type: section description: This section demonstrates a Scala 3 'Hello, World!' example. -languages: [zh-cn] +languages: [ru, zh-cn] num: 5 previous-page: taste-intro next-page: taste-repl -languages: [ru] --- > **Hint**: in the following examples try picking your preferred Scala version. diff --git a/_overviews/scala3-book/taste-intro.md b/_overviews/scala3-book/taste-intro.md index 954c8dc57b..c3b0433544 100644 --- a/_overviews/scala3-book/taste-intro.md +++ b/_overviews/scala3-book/taste-intro.md @@ -2,11 +2,10 @@ title: A Taste of Scala type: chapter description: This chapter provides a high-level overview of the main features of the Scala 3 programming language. -languages: [zh-cn] +languages: [ru, zh-cn] num: 4 previous-page: why-scala-3 next-page: taste-hello-world -languages: [ru] --- diff --git a/_overviews/scala3-book/why-scala-3.md b/_overviews/scala3-book/why-scala-3.md index 2f93b45d40..44b14845d5 100644 --- a/_overviews/scala3-book/why-scala-3.md +++ b/_overviews/scala3-book/why-scala-3.md @@ -2,11 +2,10 @@ title: Why Scala 3? type: chapter description: This page describes the benefits of the Scala 3 programming language. -languages: [zh-cn] +languages: [ru, zh-cn] num: 3 previous-page: scala-features next-page: taste-intro -languages: [ru] --- {% comment %}