Last active
November 12, 2023 00:25
-
-
Save bwnyasse/ee1023e7612ac60dd45c3f3beaa6b221 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Dart & Flutter - Training | |
* | |
* Copyright (c) Boris-Wilfried Nyasse | |
* All rights reserved | |
* | |
*/ | |
// Define a class 'Adder' that behaves like a function. | |
class Adder { | |
// 'initial' is a final integer that will be added to the sum of the list. | |
final int initial; | |
// Constructor takes an initial value. | |
Adder(this.initial); | |
// Overriding the 'call' method to make this object callable. | |
// It takes a list of integers and returns their sum added to 'initial'. | |
int call(List<int> values) => values.fold( | |
initial, | |
(a, b) => a + b, | |
); | |
} | |
// Function that takes another function as a parameter. | |
// The function parameter takes a list of integers and returns an integer. | |
void takesFun(int Function(List<int>) fun) { | |
print("Fun: ${fun([50])}"); | |
} | |
void main() { | |
// Create an instance of 'Adder' with an initial value of 10. | |
final add10 = Adder(10); | |
// The instance 'add10' can be called as if it's a function. | |
// This prints the sum of 20 and the initial value 10. | |
print(add10([20])); // 30 | |
// Calling 'add10' with a list of values. It adds all values in the list to the initial value. | |
print(add10([20, 30, 40])); // 100 | |
// 'takesFun' takes a callable object. Here 'add10' is passed and executed within 'takesFun'. | |
takesFun(add10); // 60 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment