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
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.
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.
15
13
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.
17
15
18
-
A expressão lambda possui 3 partes:
16
+
The lambda expression has 3 parts:
19
17
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
28
26
29
-
Exemplos de expressões lambda:
27
+
Examples of lambda expressions:
30
28
31
29
* `i -> System.out.println(i)`
32
30
* `(Integer i) -> System.out.println(i)`
33
31
* `(Integer i) -> { System.out.println(i); }`
34
32
* `(Integer i) -> { return i + 1; }`
35
33
* `(i, j, k) -> { return i + j + k; }`
36
34
* `(i, j, k) -> System.out.println(i + j + k)`
37
-
* `() -> System.out.println("nada")`
35
+
* `() -> System.out.println("nothing")`
38
36
39
37
//-
40
38
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.
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.
50
48
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.
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.
67
65
+
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.
69
67
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.
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.
89
87
+
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.
91
89
92
-
. Declarações de expressões lambda podem ser completas ou simplificadas.
90
+
. Declarations of lambda expressions can be complete or simplified.
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.
144
142
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.
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.
156
152
+
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.
158
156
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.
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.
168
166
169
-
.Referências
167
+
.References
170
168
****
171
169
172
170
* Implementing Functional Interfaces with Lambdas
173
171
+
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.
175
173
176
174
* Using Variables in Lambdas
177
175
+
@@ -181,4 +179,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
181
179
182
180
* https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html[Lambda Expressions.] The Java™ Tutorials.
0 commit comments