Método y tipos
Java declara el tipo de retorno y los tipos de los parámetros.
const isAdult = (age: number): boolean => age >= 18;public boolean isAdult(int age) {
return age >= 18;
}public boolean isAdult(int age) {
return age >= 18;
}PRÁCTICA · REPASO PARA LEER Y ESCRIBIR CÓDIGO
Una comparativa visual de las formas que más vas a reconocer en el código. Cambia el target desde arriba o desde el selector de esta página.
Elige el target de Java en la barra superior. Los bloques se actualizarán juntos. Java 8/11 va primero porque es sintaxis compatible con proyectos antiguos.
Pistas de versión: `record` desde Java 16, `var` local desde Java 10, `List.of` desde Java 9 y `Stream.toList()` desde Java 16. El target del proyecto puede impedir usarlos aunque tengas un JDK más nuevo.
Java declara el tipo de retorno y los tipos de los parámetros.
const isAdult = (age: number): boolean => age >= 18;public boolean isAdult(int age) {
return age >= 18;
}public boolean isAdult(int age) {
return age >= 18;
}Una interface TS describe una forma de objeto; record ofrece una forma corta e inmutable desde Java 16.
interface User {
id: number;
name: string;
active: boolean;
}public class User {
private final Long id;
private final String name;
private final boolean active;
public User(Long id, String name, boolean active) {
this.id = id;
this.name = name;
this.active = active;
}
public Long getId() { return id; }
public String getName() { return name; }
public boolean isActive() { return active; }
}public record User(Long id, String name, boolean active) {}Los streams encadenan operaciones; Java 8 usa Collectors.toList().
const names = users
.filter(user => user.active)
.map(user => user.name);List<String> names = users.stream()
.filter(User::isActive)
.map(User::getName)
.collect(Collectors.toList());List<String> names = users.stream()
.filter(User::active)
.map(User::name)
.toList();Optional existe desde Java 8. Sigue el uso que ya tenga el proyecto.
const displayName = user?.name ?? 'Unknown';String displayName = Optional.ofNullable(user)
.map(User::getName)
.orElse("Unknown");String displayName = Optional.ofNullable(user)
.map(User::name)
.orElse("Unknown");Spring MVC suele escribir el flujo como una llamada síncrona.
router.get('/users/:id', async (req, res) => {
const user = await service.find(req.params.id);
res.json(user);
});@GetMapping("/users/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.findById(id);
}@GetMapping("/users/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.findById(id);
}No captures una excepción para ocultarla; tradúcela o recupérala.
try {
await saveUser(user);
} catch (error) {
console.error(error);
}try {
userService.save(user);
} catch (RuntimeException ex) {
log.error("Could not save user", ex);
throw ex;
}try {
userService.save(user);
} catch (RuntimeException ex) {
log.error("Could not save user", ex);
throw ex;
}