Skip to content

Commit

Permalink
feat(lambda): 🎸 functional interfaces, translated
Browse files Browse the repository at this point in the history
Refers: #6
  • Loading branch information
rcmoutinho committed Sep 11, 2019
1 parent 54cd157 commit ea63716
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 77 deletions.
76 changes: 37 additions & 39 deletions book/04-lambda/sections/01-functional-interfaces.asc
Original file line number Diff line number Diff line change
@@ -1,59 +1,57 @@
:java-package: src/org/j6toj8/lambda
:section-java-package: ../../../{java-package}

=== Interfaces Funcionais (Functional Interfaces)
=== Functional Interfaces

.Objetivo
.Objective
--------------------------------------------------
Define and write functional interfaces and describe the interfaces of the java.util.function package.
-
Definir e escrever interfaces funcionais e descrever as interfaces do pacote java.util.function.
--------------------------------------------------

Interfaces funcionais são um novo tipo de Interface do Java. Nesta seção serão apresentados os conceitos e na seção de <<book/04-lambda/sections/02-lambda-expression.asc#lambda-expression,Expressões Lambda>> será possível ver como utilizá-las.
Functional interfaces are a new type of Java Interface. In this section the concepts will be presented and in the <<book/04-lambda/sections/02-lambda-expression.asc#lambda-expression,Lambda Expressions>> section you will see how to use them.

. Interfaces Funcionais são aquelas que possuem apenas um método abstrato, chamado de "método funcional".
. É recomendada a utilização da anotação `@FunctionalInterface`, mas não obrigatório.
. Functional Interfaces are those that have only one abstract method, called the "functional method".
. The use of the `@FunctionalInterface` annotation is recommended, but not required.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_Basic.java
----
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Basic.java[tag=code]
----
+
A anotação `@FunctionalInterface` garante, em tempo de compilação, que esta interface é funcional. Também indica para outros desenvolvedores que ela foi criada com o intuito de ser utilizada em expressões lambda, e por isso não se deve criar outros métodos abstratos dentro dela.
The `@FunctionalInterface` annotation ensures at compile time that this interface is functional. It also indicates to other developers that it was created for use in lambda expressions, so you should not create other abstract methods within it.

. Métodos adicionais que sejam `default` ou `static` não fazem com que a interface deixe de ser funcional.
. Additional methods that are `default` or `static` don't make the interface to be functional.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java
----
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java[tag=code]
----
+
Lembre-se que os métodos `static` em interfaces podem ser chamados diretamente, como `Executavel.execute(...)`. Dessa forma, não há interferência no fato da interface ser funcional.
Remember that `static` methods on interfaces can be called directly, such as `Executable.execute (...)`. Thus, there is no interference in the fact that the interface is functional.
+
Por outro lado, os métodos `default` só podem ser chamados caso você possua uma instância da interface, porém eles já possuem uma implementação padrão.
On the other hand, `default` methods can only be called if you have an instance of the interface, but they already have a default implementation.
+
Em caso de dúvidas sobre `static` ou `default` em interfaces, volte na seção de "Métodos _static_ e _default_ em Interfaces".
If you have questions about `static` or `default` in interfaces, go back to the _"Static and default methods of an interface"_ section.

. Sobrescrever na interface um método público de `java.lang.Object` também não faz com que ela deixe de ser funcional.
. Overriding a public method of `java.lang.Object` in the interface doesn't turn it to a no functional interface.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_OverrideObject.java
----
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_OverrideObject.java[tag=code]
----

. Uma interface que estende outra sem acrescentar métodos abstratos também pode ser funcional.
. An interface that extends another without adding abstract methods can also be functional.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_Extends.java
----
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Extends.java[tag=code]
----

. Se uma interface estende outra que é funcional, porém acrescenta novos métodos abstratos, ela não é funcional.
. If one interface extends another that is functional but adds new abstract methods, it is not functional.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java
Expand All @@ -69,68 +67,68 @@ include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Extend
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java[tag=code]
----

. Utilizar a anotaçao `@FunctionalInterface` em qualquer tipo que não seja uma interface causa um erro de compilação.
. Using the `@FunctionalInterface` annotation on any type other than an interface causes a compilation error.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java
----
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java[tag=code]
----

. Os métodos funcionais podem ter qualquer tipo de retorno.
. Functional methods can have any return.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_ReturnType.java
----
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_ReturnType.java[tag=code]
----

. Interfaces funcionais são feitas com o intuito de serem utilizadas em expressões lambda, mas o código também irá compilar normalmente caso uma classe a implemente.
. Functional interfaces are meant to be used in lambda expressions, but the code will also compile normally if a class implements it.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_Implement.java
----
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Implement.java[tag=code]
----
+
Esse é apenas um exemplo para você saber que essa implementação não gera erro de compilação, mas *não* utilize interfaces funcionais dessa forma. Na seção de Expressões Lambda você verá como as interfaces funcionais devem ser utilizadas na prática.
This is just an example for you to know that this implementation does not generate compilation errors, but *does not* use functional interfaces in this way. In the Lambda Expressions section, you will see how functional interfaces should be used in practice.

==== Interfaces Funcionais do pacote `java.util.function`
==== Functional Interfaces from `java.util.function` package

As interfaces descritas aqui estão disponíveis no pacote `java.util.function`. Nesta seção serão apresentadas apenas suas definições, pois há posteriormente uma seção específica para tratar dos exemplos de cada uma.
The interfaces described here are available in the `java.util.function` package. This section will present only its definitions, as there is later a specific section to deal with the examples of each.

Existem outras interfaces nesse pacote além das listadas aqui, porém são apenas específicas para lidar com tipos primitivos, seguindo as mesmas definições.
There are other interfaces in this package besides those listed here, but they are only specific to dealing with primitive types, following the same definitions.

* `Supplier<T>`: Representa um fornecedor de resultados.
* `Supplier<T>`: Represents a results provider.
+
Um `Supplier` literalmente apenas fornece dados ou resultados para alguém. Um gerador de números sequenciais, por exemplo, pode ser um `Supplier`.
A `Supplier` literally only provides data or results to someone. A sequential number generator, for example, may be a `Supplier`.

* `Consumer<T>`: Representa uma operação que aceita uma única entrada e não possui retorno.
* `BiConsumer<T,U>`: Representa uma operação que aceita duas entradas e não possui retorno.
* `Consumer<T>`: Represents an operation that accepts a single entry and has no return.
* `BiConsumer<T, U>`: Represents an operation that accepts two inputs and has no return.
+
Os `Consumer` são praticamente o inverso dos `Supplier`, pois eles apenas recebem dados ou informações e os tratam de alguma forma.
`Consumers` are pretty much the opposite of `Supplier`, as they only receive data or information and treat them in some way.

* `Function<T,R>`: Representa uma função que aceita um argumento e produz um retorno.
* `BiFunction<T,U,R>`: Representa uma função que aceita dois argumentos e produz um retorno.
* `Function<T, R>`: Represents a function that accepts an argument and produces a return.
* `BiFunction<T, U, R>`: Represents a function that takes two arguments and produces a return.
+
As `Function` são mais parecidas com as funções que já conhecemos. Elas recebem dados e produzem um retorno.
The `Function` are more similar to the functions we already know. They receive data and produce a return.

* `Predicate<T>`: Representa uma proposição (função de valor booleano) de um argumento.
* `BiPredicate<T,U>`: Representa uma proposição (função de valor booleano) de dois argumentos.
* `Predicate<T>`: Represents a proposition (Boolean value function) of an argument.
* `BiPredicate<T, U>`: Represents a proposition (Boolean value function) of two arguments.
+
Os `Predicate` são parecidos com as `Function`, porém sempre retornam um resultado booleano, por isso são utilizados para "testes" de verdadeiro ou falso.
`Predicate` is similar to `Function`, but always returns a Boolean result, so it is used for true or false "tests".

* `UnaryOperator<T>`: Representa uma operação em um único operador que produz um resultado do mesmo tipo dele.
* `BinaryOperator<T>`: Representa uma operação em dois operadores que produz um resultado do mesmo tipo deles.
* `UnaryOperator<T>`: Represents an operation on a single operator that produces a result of the same type as it.
* `BinaryOperator<T>`: Represents an operation on two operators that produces a result of the same type as them.
+
Os `Operator` são especializações de `Function`, pois apesar de também sempre recebem e produzirem resultados, as entradas e saídas são sempre do mesmo tipo.
The `Operator` are `Function` specializations, because although they also always receive and produce results, the inputs and outputs are always the same type.

.Referências
.References
****
* Introducing Functional Programming
+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 52). Wiley. Edição do Kindle.
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 52). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-functional-interfaces[Functional Interfaces in Java 8.]
Expand All @@ -140,4 +138,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html[Lambda Expressions.] The Java™ Tutorials.
****
****
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
public class FunctionalInterfaces_Basic {

// tag::code[]
@FunctionalInterface // a anotação não é obrigatória
interface Executavel { // interface funcional
void execute(); // método funcional
@FunctionalInterface // annotation is not required
interface Executavel { // functional interface
void execute(); // functional method
}
// end::code[]
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ public class FunctionalInterfaces_ClassCompilationError {

// tag::code[]
@FunctionalInterface
interface Executavel { // interface funcional
void execute(); // método funcional
interface Executable { // functional interface
void execute(); // functional method
}

@FunctionalInterface
class Piloto { // NÃO COMPILA!
// apenas interfaces podem ser anotadas com @FunctionalInterface
class Pilot { // NOT COMPILING!
// only interfaces can be annotated with @FunctionalInterface
}
// end::code[]
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ public class FunctionalInterfaces_DefaultStatic {

// tag::code[]
@FunctionalInterface
interface Executavel { // interface funcional
void execute(); // método funcional
interface Executable { // functional interface
void execute(); // functional method

// métodos adicionais static são permitidos
static void execute(Executavel... executaveis) {
for (Executavel executavel : executaveis) {
executavel.execute();
// additional static methods are allowed
static void execute(Executable... executables) {
for (Executable executable : executables) {
executable.execute();
}
}

// métodos adicionais default são permitidos
default void executeDuasVezes() {
// additional default methods are allowed
default void executeTwice() {
execute();
execute();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ public class FunctionalInterfaces_Extends {

// tag::code[]
@FunctionalInterface
interface Executavel { // interface funcional
void execute(); // método funcional
interface Executable { // functional interface
void execute(); // functional method
}

@FunctionalInterface
interface Aplicacao extends Executavel {
// também é uma interface funcional
interface Application extends Executable {
// It is also a functional interface
}
// end::code[]
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ public class FunctionalInterfaces_ExtendsNewMethod {

// tag::code[]
@FunctionalInterface
interface Executavel { // interface funcional
void execute(); // método funcional
interface Executable { // functional interface
void execute(); // functional method
}

@FunctionalInterface
interface Application extends Executable {
// It is NOT a functional interface as it has 2 abstract methods: execute (inherited) and init.
void init();
}

interface Aplicacao extends Executavel {
// NÃO é uma interface funcional, pois possui 2 métodos abstratos: execute (herdado) e inicie.
void inicie();
}
// end::code[]
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ public class FunctionalInterfaces_Implement {

// tag::code[]
@FunctionalInterface
interface Executavel { // interface funcional
String execute(); // método funcional
interface Executable { // functional interface
String execute(); // functional method
}

class Pessoa implements Executavel {
// COMPILA!
// interfaces funcionais, como Corredor, não foram feitas para serem implementadas dessa forma
// porém é possível e o código compila normalmente
class Person implements Executable {

// COMPILES!
// functional interfaces, such as Executable, were not meant to be implemented this way but they are possible, and code compiles normally.

@Override
public String execute() {
return "Executando";
return "Executing";
}
}
// end::code[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ public class FunctionalInterfaces_OverrideObject {

// tag::code[]
@FunctionalInterface
interface Executavel { // interface funcional
void execute(); // método funcional
interface Executable { // functional interface
void execute(); // functional method

// sobrescrevendo métodos de Object
// overriding Object methods
@Override
String toString();
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ public class FunctionalInterfaces_ReturnType {

// tag::code[]
@FunctionalInterface
interface Executavel { // interface funcional
String execute(); // método funcional com retorno
interface Executable { // functional interface
String execute(); // functional interface with return
}
// end::code[]
}

0 comments on commit ea63716

Please sign in to comment.