CodeBlanks Logo Icon CodeBlanks

Summary - Functions

Combine arrow, named and first-class to write a math helper.

Summary - Functions

This group covered the building blocks of functions. void marks no return; int, String and friends mark a returned value. return sends the value and ends the function.

The arrow => shortens single-line returns. Named and positional parameters build flexible signatures; required is mandatory, defaults guard against missing calls.

Being first-class, functions travel as values; you apply callbacks and higher-order patterns. The final task blends all of this into a small math helper.

Practice Triple compute

Define a triple(int n) arrow function whose body is n * 3. Add a print(triple(7)) call inside main.

Starter code

main.dart
void main() {
  // define the triple arrow function

  // print the result
}

Sample solution

main.dart
int triple(int n) => n * 3;

void main() {
  print(triple(7));
}

Expected output

21

Practice Math helper

Define a doubleIt(int n) arrow function (n * 2). Define an apply(int Function(int) f, int x) higher-order function (print(f(x))). Add an apply(doubleIt, 6) call inside main.

Starter code

main.dart
void main() {
  // define doubleIt and apply

  // add a call
}

Sample solution

main.dart
int doubleIt(int n) => n * 2;

void apply(int Function(int) f, int x) {
  print(f(x));
}

void main() {
  apply(doubleIt, 6);
}

Expected output

12

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is an arrow function?

  • int f(int n) { return n; }
  • int f(int n) { n; }
  • void f(int n) => return n;
  • int f(int n) => n; Correct answer

Explanation: the => marks an arrow function.

2 Match the concepts

Term Meaning
void No return
=> Arrow function
required Mandatory named
Function(int) Function type

3 Named call

Question
void greet({required String name}) { print(name); }
void main() { greet(____); }
Answer
void greet({required String name}) { print(name); }
void main() { greet(name: 'Ayşe'); }

Explanation: a named parameter is called as name: value.

All lessons in Beginner