Funciones
## Objetivos de Aprendizaje
- Definir y llamar funciones
- Comprender parametros y valores de retorno
- Dominar parametros opcionales y nombrados
- Aprender funciones flecha y typedefs
## Definiendo Funciones
### Estructura Basica
```dart
void greet() {
print('Hola!');
}
void main() {
greet(); // Hola!
}
```
### Funcion con Tipo de Retorno
```dart
int add(int a, int b) {
return a + b;
}
void main() {
int result = add(5, 3);
print(result); // 8
}
```
### Inferencia de Tipo de Retorno
```dart
void main() {
// Dart puede inferir el tipo de retorno para funciones simples
var add = (int a, int b) => a + b;
print(add(5, 3)); // 8
}
```
## Parametros
### Parametros Posicionales
```dart
void printName(String firstName, String lastName) {
print('$firstName $lastName');
}
void main() {
printName('John', 'Doe'); // John Doe
}
```
### Parametros Posicionales Opcionales
```dart
String greet(String name, [String? title]) {
if (title != null) {
return '$title $name';
}
return name;
}
void main() {
print(greet('Alice')); // Alice
print(greet('Bob', 'Sr.')); // Sr. Bob
}
```
### Valores de Parametros por Defecto
```dart
String greet(String name, [String title = 'Sr.']) {
return '$title $name';
}
void main() {
print(greet('Alice')); // Sr. Alice
print(greet('Bob', 'Dr.')); // Dr. Bob
}
```
### Parametros Nombrados
```dart
void createUser({
required String name,
int age = 18,
String city = 'Unknown',
}) {
print('User: $name, Age: $age, City: $city');
}
void main() {
createUser(name: 'Alice', age: 25, city: 'NYC');
createUser(name: 'Bob'); // Usa valores por defecto para age y city
}
```
### Parametros Nombrados Requeridos
```dart
void createUser({
required String name,
required int age, // Debe proporcionarse
String? email, // Opcional
}) {
print('User: $name, Age: $age, Email: $email');
}
void main() {
createUser(name: 'Alice', age: 25); // OK
// createUser(name: 'Bob'); // Error: age es requerido
}
```
## Valores de Retorno
### void (Sin Retorno)
```dart
void printSum(int a, int b) {
print('Suma: ${a + b}');
}
```
### Retorno Temprano
```dart
String getGrade(int score) {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
return 'F';
}
```
### Multiples Retornos (Clausulas de Guardia)
```dart
bool validate(int age, String? name) {
if (age < 0) return false;
if (name == null || name.isEmpty) return false;
return true;
}
```
## Funciones Flecha
### Expresion Simple
```dart
int square(int x) => x * x;
void main() {
print(square(5)); // 25
}
```
### Con Cuerpo de Bloque
```dart
int square(int x) {
return x * x;
}
```
### En Colecciones
```dart
void main() {
var numbers = [1, 2, 3, 4, 5];
var doubled = numbers.map((n) => n * 2);
print(doubled.toList()); // [2, 4, 6, 8, 10]
var evens = numbers.where((n) => n % 2 == 0);
print(evens.toList()); // [2, 4]
}
```
## Funciones Annimas
### Expresiones Lambda
```dart
void main() {
var multiply = (int a, int b) => a * b;
print(multiply(3, 4)); // 12
var numbers = [1, 2, 3];
numbers.forEach((n) => print(n));
}
```
### Clausura
```dart
Function makeAdder(int addBy) {
return (int n) => n + addBy;
}
void main() {
var add2 = makeAdder(2);
var add10 = makeAdder(10);
print(add2(5)); // 7
print(add10(5)); // 15
}
```
## Funciones de Orden Superior
### Funciones como Parametros
```dart
void executeTwice(Function f) {
f();
f();
}
void main() {
executeTwice(() => print('Hola'));
}
```
### Funciones que Retornan Funciones
```dart
Function operation(String type) {
switch (type) {
case 'add':
return (a, b) => a + b;
case 'subtract':
return (a, b) => a - b;
default:
return (a, b) => 0;
}
}
void main() {
var add = operation('add');
print(add(10, 5)); // 15
}
```
## Typedef
### Alias de Tipo de Funcion
```dart
typedef Calculate = int Function(int, int);
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
void main() {
Calculate calc = add;
print(calc(10, 5)); // 15
calc = subtract;
print(calc(10, 5)); // 5
}
```
### Con Parametros Nombrados
```dart
typedef UserCreator = User Function({
required String name,
required int age,
});
User createUser({required String name, required int age}) {
return User(name, age);
}
void main() {
UserCreator creator = createUser;
var user = creator(name: 'Alice', age: 30);
}
```
## Recursion
### Factorial
```dart
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
void main() {
print(factorial(5)); // 120
}
```
### Alternativa Iterativa
```dart
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
```
## Alcance
### Variables Locales
```dart
void main() {
var x = 'exterior';
void inner() {
var x = 'interior';
print(x); // interior (sombrea a exterior)
}
inner();
print(x); // exterior
}
```
## Resumen
- Funciones: `tipo_retorno nombre(parametros) { }`
- Flecha: `int square(int x) => x * x;`
- Parametros nombrados: `func({required int a, int b = 5})`
- Parametros posicionales opcionales: `func(a, [b])`
- `typedef` crea alias de tipos de funcion
- Funciones anonimas: `(params) => expresion`
- Funciones son de primera clase: pueden pasarse/devolverse
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →