You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: _ru/scala3/book/why-scala-3.md
+49-44Lines changed: 49 additions & 44 deletions
Original file line number
Diff line number
Diff line change
@@ -15,27 +15,28 @@ next-page: taste-intro
15
15
Использование Scala, и Scala 3 в частности, дает много преимуществ.
16
16
Трудно перечислить их все, но “топ десять” может выглядеть так:
17
17
18
-
1. Scala embraces a fusion of functional programming (FP) and object-oriented programming (OOP)
19
-
2. Scala is statically typed, but often feels like a dynamically typed language
20
-
3. Scala’s syntax is concise, but still readable; it’s often referred to as _expressive_
21
-
4._Implicits_in Scala 2 were a defining feature, and they have been improved and simplified in Scala 3
22
-
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
23
-
6. Scala can be used on the server, and also in the browser with[Scala.js](https://www.scala-js.org)
24
-
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
25
-
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
26
-
9.The Scala ecosystem offers the most modern FP libraries in the world
27
-
10.Strong type system
18
+
1. Scala сочетает в себе функциональное программирование (ФП) и объектно-ориентированное программирование (ООП)
19
+
2. Scala статически типизирован, но часто ощущается как язык с динамической типизацией
20
+
3.Синтаксис Scala лаконичен, но все же удобочитаем; его часто называют _выразительным_
21
+
4._Implicits_в Scala 2 были определяющей функцией, а в Scala 3 они были улучшены и упрощены
22
+
5. Scala легко интегрируется с Java, поэтому вы можете создавать проекты со смешанным кодом Scala и Java, а код Scala легко использует тысячи существующих библиотек Java
23
+
6. Scala можно использовать на сервере, а также в браузере со[Scala.js](https://www.scala-js.org)
24
+
7.Стандартная библиотека Scala содержит десятки готовых функциональных методов, позволяющих сэкономить ваше время и значительно сократить потребность в написании пользовательских циклов `for`и алгоритмов
25
+
8. “Best practices”, встроенные в Scala, поддерживают неизменность, анонимные функции, функции высшего порядка, сопоставление с образцом, классы, которые не могут быть расширены по умолчанию, и многое другое
26
+
9.Экосистема Scala предлагает самые современные ФП библиотеки в мире
27
+
10.Сильная система типов
28
28
29
-
## 1) FP/OOP fusion
30
29
31
-
More than any other language, Scala supports a fusion of the FP and OOP paradigms.
32
-
As Martin Odersky has stated, the essence of Scala is a fusion of functional and object-oriented programming in a typed setting, with:
30
+
## 1) Слияние ФП/ООП
33
31
34
-
- Functions for the logic, and
35
-
- Objects for the modularity
32
+
Больше, чем любой другой язык, Scala поддерживает слияние парадигм ФП и ООП.
33
+
Как заявил Мартин Одерски, сущность Scala — это слияние функционального и объектно-ориентированного программирования в типизированной среде с:
36
34
37
-
Possibly some of the best examples of modularity are the classes in the standard library.
38
-
For instance, a `List` is defined as a class---technically it’s an abstract class---and a new instance is created like this:
35
+
- Функции для логики и
36
+
- Объекты для модульности
37
+
38
+
Возможно, одними из лучших примеров модульности являются классы стандартной библиотеки.
39
+
Например, `List` определяется как класс---технически это абстрактный класс---и новый экземпляр создается следующим образом:
39
40
40
41
{% tabs list %}
41
42
{% tab 'Scala 2 and 3' for=list %}
@@ -45,10 +46,12 @@ val x = List(1, 2, 3)
45
46
{% endtab %}
46
47
{% endtabs %}
47
48
48
-
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`.
49
-
Those types are similarly composed of other small, modular units of code.
49
+
Однако то, что кажется программисту простым `List`, на самом деле построено из комбинации нескольких специализированных типов,
50
+
включая трейты с именами `Iterable`, `Seq` и `LinearSeq`.
51
+
Эти типы также состоят из других небольших модульных единиц кода.
50
52
51
-
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:
53
+
В дополнение к построению типа наподобие `List` из серии модульных трейтов,
54
+
`List` API также состоит из десятков других методов, многие из которых являются функциями высшего порядка:
In those examples, the values in the list can’t be modified.
67
-
The`List`class is immutable, so all of those methods return new values, as shown by the data in each comment.
69
+
В этих примерах значения в списке не могут быть изменены.
70
+
Класс`List`неизменяем, поэтому все эти методы возвращают новые значения, как показано в каждом комментарии.
68
71
69
-
## 2) A dynamic feel
72
+
## 2) Ощущение динамики
70
73
71
-
Scala’s _type inference_ often makes the language feel dynamically typed, even though it’s statically typed.
72
-
This is true with variable declaration:
74
+
_Вывод типов_ (_type inference_) в Scala часто заставляет язык чувствовать себя динамически типизированным, даже если он статически типизирован.
75
+
Это верно для объявления переменной:
73
76
74
77
{% tabs dynamic %}
75
78
{% tab 'Scala 2 and 3' for=dynamic %}
@@ -82,7 +85,7 @@ val stuff = ("fish", 42, 1_234.5)
82
85
{% endtab %}
83
86
{% endtabs %}
84
87
85
-
It’s also true when passing anonymous functions to higher-order functions:
88
+
Это также верно при передаче анонимных функций функциям высшего порядка:
86
89
87
90
{% tabs dynamic-hof %}
88
91
{% tab 'Scala 2 and 3' for=dynamic-hof %}
@@ -95,7 +98,7 @@ list.filter(_ < 4)
95
98
{% endtab %}
96
99
{% endtabs %}
97
100
98
-
and when defining methods:
101
+
и при определении методов:
99
102
100
103
{% tabs dynamic-method %}
101
104
{% tab 'Scala 2 and 3' for=dynamic-method %}
@@ -105,27 +108,27 @@ def add(a: Int, b: Int) = a + b
105
108
{% endtab %}
106
109
{% endtabs %}
107
110
108
-
This is more true than ever in Scala 3, such as when using [union types][union-types]:
111
+
Это как никогда верно для Scala 3, например, при использовании [типов объединения][union-types]:
109
112
110
113
{% tabs union %}
111
114
{% tab 'Scala 3 Only' for=union %}
112
115
```scala
113
-
//union type parameter
116
+
//параметр типа объединения
114
117
defhelp(id: Username|Password) =
115
118
valuser= id match
116
119
caseUsername(name) => lookupName(name)
117
120
casePassword(hash) => lookupPassword(hash)
118
-
//more code here ...
121
+
//дальнейший код ...
119
122
120
-
//union type value
123
+
//значение типа объединения
121
124
valb:Password|Username=if (true) name else password
122
125
```
123
126
{% endtab %}
124
127
{% endtabs %}
125
128
126
-
## 3) Concise syntax
129
+
## 3) Лаконичный синтаксис
127
130
128
-
Scala is a low ceremony, “concise but still readable” language. For instance, variable declaration is concise:
131
+
Scala — это неформальный, “краткий, но все же читабельный“ язык. Например, объявление переменной лаконично:
129
132
130
133
{% tabs concise %}
131
134
{% tab 'Scala 2 and 3' for=concise %}
@@ -137,7 +140,7 @@ val c = List(1,2,3)
137
140
{% endtab %}
138
141
{% endtabs %}
139
142
140
-
Creating types like traits, classes, and enumerations are concise:
143
+
Создание типов, таких как трейты, классы и перечисления, является кратким:
141
144
142
145
{% tabs enum %}
143
146
{% tab 'Scala 3 Only' for=enum %}
@@ -160,7 +163,7 @@ case class Person(
160
163
{% endtab %}
161
164
{% endtabs %}
162
165
163
-
Higher-order functions are concise:
166
+
Функции высшего порядка кратки:
164
167
165
168
{% tabs list-hof %}
166
169
{% tab 'Scala 2 and 3' for=list-hof %}
@@ -172,19 +175,21 @@ list.map(_ * 2)
172
175
{% endtab %}
173
176
{% endtabs %}
174
177
175
-
All of these expressions and many more are concise, and still very readable: what we call _expressive_.
178
+
Все эти и многие другие выражения кратки и при этом очень удобочитаемы: то, что мы называем _выразительным_ (_expressive_).
176
179
177
-
## 4) Implicits, simplified
180
+
## 4) Implicits, упрощение
178
181
179
-
Implicits in Scala 2 were a major distinguishing design feature.
180
-
They represented _the_ fundamental way to abstract over context, with a unified paradigm that served a great variety of use cases, among them:
182
+
Implicits в Scala 2 были главной отличительной особенностью дизайна.
183
+
Они представляли собой фундаментальный способ абстрагирования от контекста с единой парадигмой,
184
+
которая обслуживала множество вариантов использования, среди которых:
181
185
182
-
-Implementing [type classes]({% link _overviews/scala3-book/ca-type-classes.md %})
183
-
-Establishing context
184
-
-Dependency injection
185
-
-Expressing capabilities
186
+
-Реализация [типовых классов]({% link _overviews/scala3-book/ca-type-classes.md %})
187
+
-Установление контекста
188
+
-Внедрение зависимости
189
+
-Выражение возможностей
186
190
187
-
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.
191
+
С тех пор другие языки приняли аналогичные концепции, все из которых являются вариантами основной идеи вывода терминов:
192
+
при заданном типе компилятор синтезирует “канонический” термин, имеющий этот тип.
188
193
189
194
While implicits were a defining feature in Scala 2, their design has been greatly improved in Scala 3:
0 commit comments