Skip to content

Commit 322d571

Browse files
committed
feat(lambda): 🎸 lambda expression, translated
Refers: #6
1 parent e8ced1d commit 322d571

12 files changed

+117
-117
lines changed

book/04-lambda/sections/02-lambda-expression.asc

Lines changed: 46 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -2,80 +2,78 @@
22
:section-java-package: ../../../{java-package}
33

44
[[lambda-expression]]
5-
=== Expressões Lambda (Lambda Expression)
5+
=== Lambda Expression
66

7-
.Objetivo
7+
.Objective
88
--------------------------------------------------
99
Describe a lambda expression; refactor the code that uses an anonymous inner class to use a lambda expression; describe type inference and target typing.
10-
-
11-
Descrever uma expressão lambda; refatorar código que usa classes anônimas internas para usar expressões lambda; descrever a inferência de tipos e tipos esperados.
1210
--------------------------------------------------
1311

14-
Expressões Lambda são parecidas com classes anônimas, porém só possuem a implementação dos métodos. Por isso, são como "métodos anônimos", que podem ser passados via variáveis.
12+
Lambda expressions are similar to anonymous classes, but only have the implementation of the methods. Therefore, they are like "anonymous methods" that can be passed via variables.
1513

16-
É essencial o entendimento de funções lambda, e das variações em sua sintaxe, para compreender as próximas seções de Interfaces Funcionais Pré-Construídas e de Referências a métodos.
14+
Understanding lambda functions, and variations in their syntax, is essential to understanding the next sections of Built-in Interfaces and Method References.
1715

18-
A expressão lambda possui 3 partes:
16+
The lambda expression has 3 parts:
1917

20-
. Uma lista de parâmetros, separados por vírgula
21-
* Algumas vezes possui parênteses
22-
* Algumas vezes possui o tipo das variáveis
23-
. O "arrow token", que sempre é escrito como `\->`
24-
. Um corpo, que pode ou não estar entre chaves
25-
* Pode possuir mais de uma linha
26-
* Algumas vezes possui um `return`
27-
* Algumas vezes possui ponto e vírgula
18+
. A comma-separated list of parameters
19+
* Sometimes has parentheses
20+
* Sometimes has variable type
21+
. The "arrow token", which is always written as `\->`
22+
. A body, which may or may not be enclosed in braces
23+
* Can have more than one line
24+
* Sometimes has a `return`
25+
* Sometimes has semicolon
2826

29-
Exemplos de expressões lambda:
27+
Examples of lambda expressions:
3028

3129
* `i -> System.out.println(i)`
3230
* `(Integer i) -> System.out.println(i)`
3331
* `(Integer i) -> { System.out.println(i); }`
3432
* `(Integer i) -> { return i + 1; }`
3533
* `(i, j, k) -> { return i + j + k; }`
3634
* `(i, j, k) -> System.out.println(i + j + k)`
37-
* `() -> System.out.println("nada")`
35+
* `() -> System.out.println("nothing")`
3836

3937
//-
4038

41-
. Expressões lambda podem ser entendidas como uma forma diferente de declarar classes anônimas.
39+
. Lambda expressions can be understood as a different way of declaring anonymous classes.
4240
+
4341
[source,java,indent=0]
4442
.{java-package}/lambdaexpression/LambdaExpression_AnonymousClass.java
4543
----
4644
include::{section-java-package}/lambdaexpression/LambdaExpression_AnonymousClass.java[tag=code]
4745
----
4846
+
49-
Veja que no exemplo acima é instanciada uma `Thread` com uma instância anônima de `Runnable`. Na segunda parte, é feito a mesma coisa de forma muito mais simples utilizando uma expressão lambda.
47+
Note that in the example above a `Thread` is instantiated with an anonymous instance of `Runnable`. In the second part, the same thing is done much simpler using a lambda expression.
5048

51-
. Expressões lambda são sempre utilizadas para criar instâncias de interfaces funcionais, ou seja, interfaces que possuem apenas um único método abstrato.
49+
. Lambda expressions are always used to create instances of functional interfaces, i.e., interfaces that have only a single abstract method.
5250
+
5351
[source,java,indent=0]
5452
.{java-package}/lambdaexpression/LambdaExpression_FunctionalInterface.java
5553
----
5654
include::{section-java-package}/lambdaexpression/LambdaExpression_FunctionalInterface.java[tag=code]
5755
----
5856
+
59-
.Saída no console
57+
.console output
6058
[source,console]
6159
----
62-
executei com classe anônima
63-
executei com expressão lambda
60+
performed with anonymous class
61+
performed with lambda expression
6462
----
6563
+
66-
Veja que no exemplo acima o mesmo método `executeEApresenteMensagem` é invocado duas vezes. Na primeira vez é passada uma nova classe anônima. Na segunda vez é passado uma expressão lambda.
64+
Note that in the example above the same `executeAndPresentMessage` method is invoked twice. The first time a new anonymous class is passed. The second time a lambda expression is passed.
6765
+
68-
Veja também que seria impossível criar uma expressão lambda caso a interface não fosse funcional, ou seja, tivesse mais de um método abstrato. O compilador não saberia identificar que o método `execute`, da interface `Executavel`, está sendo implementado dentro da expressão lambda.
66+
Also see that it would be impossible to create a lambda expression if the interface was not functional, i.e., it had more than one abstract method. The compiler would not be able to identify that the `execute` method of the` Executable` interface is being implemented within the lambda expression.
6967

70-
. Existem muitos métodos já disponíveis no Java 8 que se beneficiam da sintaxe de expressões lambda, como o `forEach` de listas.
68+
. There are many methods already available in Java 8 that benefit from lambda expression syntax, such as `forEach` lists.
7169
+
7270
[source,java,indent=0]
7371
.{java-package}/lambdaexpression/LambdaExpression_ForEach.java
7472
----
7573
include::{section-java-package}/lambdaexpression/LambdaExpression_ForEach.java[tag=code]
7674
----
7775
+
78-
.Saída no console
76+
.console output
7977
[source,console]
8078
----
8179
1
@@ -85,93 +83,93 @@ include::{section-java-package}/lambdaexpression/LambdaExpression_ForEach.java[t
8583
5
8684
----
8785
+
88-
Veja que o novo método `forEach` executa a expressão lambda passada como parâmetro para cada item da lista, imprimindo todos no console. A expressão lambda recebe como parâmetro um número, que é o número da lista.
86+
Note that the new `forEach` method executes the lambda expression passed as a parameter to each list item, printing them all to the console. The lambda expression takes as a parameter a number, which is the list number.
8987
+
90-
Neste caso, a interface funcional que está sendo implementada pela expressão lambda é chamada `Consumer`. Ela será explicada em detalhes em uma seção posterior, juntamente com outras interfaces funcionais padrões do Java 8. Nesta seção é importante apenas entender o que são as expressões lambda e como é sua sintaxe.
88+
In this case, the functional interface being implemented by the lambda expression is called `Consumer`. It will be explained in detail in a later section, along with other standard Java 8 functional interfaces. In this section, it is essential to understand what lambda expressions are and what their syntax is like.
9189

92-
. Declarações de expressões lambda podem ser completas ou simplificadas.
90+
. Declarations of lambda expressions can be complete or simplified.
9391
+
9492
[source,java,indent=0]
9593
.{java-package}/lambdaexpression/LambdaExpression_SimpleComplete.java
9694
----
9795
include::{section-java-package}/lambdaexpression/LambdaExpression_SimpleComplete.java[tag=code]
9896
----
9997
+
100-
As duas funções lambda acima são idênticas, porém uma é mais explícita do que a outra.
98+
The two lambda functions above are identical, but one is more explicit than the other.
10199

102-
. Os parênteses só podem ser omitidos caso não haja a declaração do *tipo*, e haja apenas *um único* argumento.
103-
. Expressões lambda que NÃO possuem argumentos também precisam dos parênteses.
100+
. Parentheses can only be omitted if there is no *type* declaration, and there is only *a single* argument.
101+
. Lambda expressions that do NOT have arguments also need parentheses.
104102
+
105103
[source,java,indent=0]
106104
.{java-package}/lambdaexpression/LambdaExpression_Parenthesis.java
107105
----
108106
include::{section-java-package}/lambdaexpression/LambdaExpression_Parenthesis.java[tag=code]
109107
----
110108

111-
. É obrigatória a utilização de chaves, ponto e vírgula e `return` (caso a função retorne algum valor) em expressões lambda com mais de uma linha.
109+
. The use of curly brackets, semicolons and `return` (if the function returns any value) is required in lambda expressions with more than one line.
112110
+
113111
[source,java,indent=0]
114112
.{java-package}/lambdaexpression/LambdaExpression_Block.java
115113
----
116114
include::{section-java-package}/lambdaexpression/LambdaExpression_Block.java[tag=code]
117115
----
118116

119-
. Ao tornar explícito o tipo de um dos argumentos, é obrigatório informar de todos.
117+
. When making the type of one of the arguments explicit, it is mandatory to inform all of them.
120118
+
121119
[source,java,indent=0]
122120
.{java-package}/lambdaexpression/LambdaExpression_VarType.java
123121
----
124122
include::{section-java-package}/lambdaexpression/LambdaExpression_VarType.java[tag=code]
125123
----
126124

127-
. Não é permitido declarar variáveis com o mesmo nome dentro da expressão lambda.
125+
. It is not allowed to declare variables with the same name within the lambda expression.
128126
+
129127
[source,java,indent=0]
130128
.{java-package}/lambdaexpression/LambdaExpression_Shadowing.java
131129
----
132130
include::{section-java-package}/lambdaexpression/LambdaExpression_Shadowing.java[tag=code]
133131
----
134132

135-
. É permitido acessar variáveis externas dentro da expressão lambda, mas somente variáveis finais ou variáveis que não são alteradas.
133+
. It is allowed to access external variables within the lambda expression, but only final variables or variables that do not change.
136134
+
137135
[source,java,indent=0]
138136
.{java-package}/lambdaexpression/LambdaExpression_AccessExternalVar.java
139137
----
140138
include::{section-java-package}/lambdaexpression/LambdaExpression_AccessExternalVar.java[tag=code]
141139
----
142140
+
143-
Perceba que o compilador identifica que a variável `x3` é alterada no final do método, e por isso, não permite que ela seja utilizada na expressão lambda.
141+
Note that the compiler identifies that the `x3` variable is changed at the end of the method, and therefore does not allow it to be used in the lambda expression.
144142

145-
. Em situações de ambiguidade, o compilador tenta descobrir o tipo da expressão lambda utilizando o contexto.
143+
. In ambiguous situations, the compiler tries to find out the type of lambda expression using the context.
146144
+
147145
[source,java,indent=0]
148146
.{java-package}/lambdaexpression/LambdaExpression_TypeInference.java
149147
----
150148
include::{section-java-package}/lambdaexpression/LambdaExpression_TypeInference.java[tag=code]
151149
----
152150
+
153-
No exemplo anterior, apenas o método `run` da interface funcional `Application` retorna uma `String`, enquanto o método `execute` da interface funcional `Executavel` não retorna nada (`void`). Isso é diferença suficiente para o compilador saber qual método chamar cada vez que `rode` é invocado.
154-
+
155-
Na primeira chamada ao método `rode`, como a expressão lambda passada retorna uma `String`, o compilador entende que essa expressão lambda é uma implementação da interface `Application`, pois o método `run` também retorna uma `String`.
151+
In the previous example, only the `run` method of the `Application` functional interface returns a `String`, while the `execute` method of the `Executable` functional interface returns nothing (`void`). This is enough difference for the compiler to know which method to call each time `doThis` is invoked.
156152
+
157-
Na segunda chamada ao método `rode`, como a expressão lambda não retorna nada (apenas imprime a `String` `"executando"`), o compilador entende que essa expressão lambda é uma implementação da interface `Executavel`, pois o método `execute` também não retorna nada.
153+
On the first call to the `doThis` method, since the passed lambda expression returns a `String`, the compiler understands that this lambda expression is an implementation of the `Application` interface, as the `run` method also returns a `String`.
154+
+
155+
On the second call to the `doThis` method, since the lambda expression returns nothing (just prints the `String` `"executing"`), the compiler understands that this lambda expression is an implementation of the `Executable` interface, because the `execute` also returns nothing.
158156

159-
. Se não for possível descobrir o tipo da expressão lambda, ocorre erro de compilação.
157+
. If the type of the lambda expression cannot be found, a compilation error occurs.
160158
+
161159
[source,java,indent=0]
162160
.{java-package}/lambdaexpression/LambdaExpression_Ambiguity.java
163161
----
164162
include::{section-java-package}/lambdaexpression/LambdaExpression_Ambiguity.java[tag=code]
165163
----
166164
+
167-
No exemplo anterior, como as duas interfaces funcionais possuem métodos com retorno `void`, o compilador não sabe qual das duas está sendo instanciada na expressão lambda, e ocorre erro de compilação. A expressão lambda, nesse exemplo, poderia ser tanto do tipo `Piloto` quanto `Corredor`, e não há como o compilador descobrir qual o desenvolvedor de fato quis utilizar.
165+
In the previous example, because both functional interfaces have a `void` method, the compiler does not know which one is being instantiated in the lambda expression, and a compilation error occurs. The lambda expression in this example could be either `Pilot` or `Runner`, and there is no way for the compiler to find out which developer actually wanted to use it.
168166

169-
.Referências
167+
.References
170168
****
171169
172170
* Implementing Functional Interfaces with Lambdas
173171
+
174-
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 55). Wiley. Edição do Kindle.
172+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 55). Wiley. Kindle Edition.
175173
176174
* Using Variables in Lambdas
177175
+
@@ -181,4 +179,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
181179
182180
* https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html[Lambda Expressions.] The Java™ Tutorials.
183181
184-
****
182+
****

src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AccessExternalVar.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,16 @@ public static void main(String[] args) {
1010
Double x2 = 2.0;
1111
Double x3 = 2.0;
1212

13-
// COMPILA - variável externa 'x1' é final e pode ser utilizada na expressão lambda
14-
UnaryOperator<Double> elevarAoX1 = (Double y) -> Math.pow(y, x1);
13+
// COMPILES - external variable 'x1' is final and can be used in lambda expression
14+
UnaryOperator<Double> raiseToX1 = (Double y) -> Math.pow(y, x1);
1515

16-
// COMPILA - variável externa 'x2' não é final, mas nunca é alterada, então pode ser utilizada dentro da expressão lambda
17-
UnaryOperator<Double> elevarAoX2 = (Double y) -> Math.pow(y, x2);
16+
// COMPILES - external variable 'x2' is not final, but never changed, so it can be used inside the lambda expression
17+
UnaryOperator<Double> raiseToX2 = (Double y) -> Math.pow(y, x2);
1818

19-
// NÃO COMPILA - variável externa 'x3' é alterada dentro desse método, então não pode ser utilizada dentro da expressão lambda
20-
UnaryOperator<Double> elevarAoX3 = (Double y) -> Math.pow(y, x3);
19+
// NOT COMPILING - external variable 'x3' is changed within this method, so it cannot be used within the lambda expression
20+
UnaryOperator<Double> raiseToX3 = (Double y) -> Math.pow(y, x3);
2121

22-
x3 = 3.0; // alteração da variável x3 não permite que ela seja utilizada em expressões lambda
22+
x3 = 3.0; // changing variable 'x3' does not allow it to be used in lambda expressions
2323
}
2424
// end::code[]
2525
}

src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Ambiguity.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,29 @@ public class LambdaExpression_Ambiguity {
44

55
// tag::code[]
66
@FunctionalInterface
7-
interface Corredor {
8-
void corra();
7+
interface Runner {
8+
void run();
99
}
1010

1111
@FunctionalInterface
12-
interface Piloto {
13-
void corra();
12+
interface Pilot {
13+
void run();
1414
}
1515

1616
static class Executor {
17-
void execute(Corredor corredor) {
18-
corredor.corra();
17+
void execute(Runner runner) {
18+
runner.run();
1919
}
2020

21-
String execute(Piloto piloto) {
22-
piloto.corra();
23-
return "correndo";
21+
String execute(Pilot pilot) {
22+
pilot.run();
23+
return "running";
2424
}
2525
}
2626

2727
public static void main(String[] args) {
2828
Executor executor = new Executor();
29-
// NÃO COMPILA - não é possível determinar o tipo da expressão lambda abaixo
29+
// NOT COMPILING - cannot determine type of lambda expression below
3030
executor.execute(() -> System.out.println("execute"));
3131
}
3232
// end::code[]

src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AnonymousClass.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@ public class LambdaExpression_AnonymousClass {
44

55
public static void main(String[] args) {
66
// tag::code[]
7-
// com classe anônima
7+
// with anonymous class
88
new Thread(new Runnable() {
99
@Override
1010
public void run() {
11-
System.out.println("Executando.");
11+
System.out.println("Executing.");
1212
}
1313
}).run();
1414

15-
// com expressão lambda
16-
new Thread(() -> System.out.println("Executando.")).run();
15+
// with lambda expression
16+
new Thread(() -> System.out.println("Executing.")).run();
1717
// end::code[]
1818
}
1919
}

src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Block.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ public class LambdaExpression_Block {
77

88
public static void main(String[] args) {
99
// tag::code[]
10-
UnaryOperator<Double> elevarAoQuadrado = (Double x) -> {
10+
UnaryOperator<Double> square = (Double x) -> {
1111
double pow = Math.pow(x, 2);
1212
return pow;
1313
};
1414

15-
Consumer<Double> imprime = (Double x) -> {
15+
Consumer<Double> print = (Double x) -> {
1616
double pow = Math.pow(x, 2);
1717
System.out.println(pow);
1818
};

src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_ForEach.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ public class LambdaExpression_ForEach {
77

88
public static void main(String[] args) {
99
// tag::code[]
10-
List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5);
11-
lista.forEach((numero) -> { System.out.println(numero); });
10+
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
11+
list.forEach((number) -> { System.out.println(number); });
1212
// end::code[]
1313
}
1414
}

src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_FunctionalInterface.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,27 @@ public class LambdaExpression_FunctionalInterface {
44

55
// tag::code[]
66
@FunctionalInterface
7-
interface Executavel { // interface funcional
8-
String execute(); // método funcional
7+
interface Executable { // functional interface
8+
String execute(); // functional method
99
}
1010

11-
private static void executeEApresenteMensagem(Executavel executavel) {
12-
String mensagem = executavel.execute();
13-
System.out.println(mensagem);
11+
private static void executeAndPresentMessage(Executable executable) {
12+
String message = executable.execute();
13+
System.out.println(message);
1414
}
1515

1616
public static void main(String[] args) {
1717

18-
// com classe anônima
19-
executeEApresenteMensagem(new Executavel() {
18+
// with anonymous class
19+
executeAndPresentMessage(new Executable() {
2020
@Override
2121
public String execute() {
22-
return "executei com classe anônima";
22+
return "performed with anonymous class";
2323
}
2424
});
2525

26-
// com expressão lambda
27-
executeEApresenteMensagem(() -> { return "executei com expressão lambda"; });
26+
// with lambda expression
27+
executeAndPresentMessage(() -> { return "performed with lambda expression"; });
2828
}
2929
// end::code[]
3030
}

0 commit comments

Comments
 (0)