Skip to content

Instantly share code, notes, and snippets.

@matey-jack
Last active September 1, 2018 16:18
Show Gist options
  • Save matey-jack/a53da62a1e58caa6df6f4b4f2e19513c to your computer and use it in GitHub Desktop.
Save matey-jack/a53da62a1e58caa6df6f4b4f2e19513c to your computer and use it in GitHub Desktop.
Four and a half ways of defining functions in Dart
import "package:test/test.dart";
// C-style declared function with block body
int increment_block(int x) {
return x + 1;
}
// declared function with expression body
int increment(int x) => x + 1;
// we can also be very terse and omit types altogether
inc(x) => x + 1;
// inline function with expression body
final increment_inline = (int x) => x + 1;
// inline function with block body
// warning: "type of function literal can't be inferred"
final increment_inline_block = (int x) {
return x + 1;
};
// to get rid of the warning, we need to give an explicit type:
final int Function(int) increment_inline_explicit = (x) {
return x + 1;
};
void main() {
// some tests just to make sure that each function runs at least once
// and has no run-time errors.
test("function declarations", () {
expect(increment(1), equals(2));
expect(inc(1), equals(2));
expect(increment_block(1), equals(2));
expect(increment_inline(1), equals(2));
// there is no run-time error on the function which produces a warning,
// since we only use it the way it is intended.
expect(increment_inline_block(1), equals(2));
expect(increment_inline_explicit(1), equals(2));
});
}
// we can simplify the type spec of the function-valued variable with a typedef:
typedef Incrementer = int Function(int);
final Incrementer increment = (x) {
return x + 1;
};
// This is really useful when declaring a function argument of that type.
// For example:
void processAll(List<int> numbers, Incrementer fun, String message) { ... }
// Note that in a `typedef` (but only here!) we can also use another syntax
// to accomplish the same thing. I find that quite confusing and wonder why Dart allows this.
typedef int Incrementer(int);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment