A. Dumais
A. Dumais

Reputation: 305

Are there now two ways to use typedef in Dart?

I see multiple forms of typedef throughout dart and flutter libraries, but I can't quite make sense of it. There's this example in framework.dart:

typedef ElementVisitor = void Function(Element element);

And there's this example (https://medium.com/@castellano.mariano/typedef-in-dart-40e96d3941f9):

typedef String Join(String a, String b);

I don't quite understand the difference of their uses. Maybe this has something to do with why I can't find the definition of "Function" anywhere in the Dart or Flutter libraries. But then again I can find other typedef's just fine in the framework.dart file.

Upvotes: 3

Views: 2589

Answers (2)

Falyoun
Falyoun

Reputation: 3976

As docs refers

There is an old and new way of typedef

in general: the new way is a bit clearer and more readable.

in details:

typedef G = List<int> Function(int); // New form.
typedef List<int> H(int i); // Old form.

Note that the name of the parameter is required in the old form, but the type may be omitted. In contrast, the type is required in the new form, but the name may be omitted.

As well as

The reason for having two ways to express the same thing is that the new form seamlessly covers non-generic functions as well as generic ones, and developers might prefer to use the new form everywhere, for improved readability.

There is a difference between declaring a generic function type and declaring a typedef which takes a type argument. The former is a declaration of a single type which describes a certain class of runtime entities: Functions that are capable of accepting some type arguments as well as some value arguments, both at runtime. The latter is a compile-time mapping from types to types: It accepts a type argument at compile time and returns a type, which may be used, say, as a type annotation. We use the phrase parameterized typedef to refer to the latter. Dart has had support for parameterized typedefs for a while, and the new syntax supports parameterized typedefs as well. Here is an example of a parameterized typedef, and a usage thereof:

typedef I<T> = List<T> Function(T); // New form.
typedef List<T> J<T>(T t); // Old form.
I<int> myFunction(J<int> f) => f;

For more info

Upvotes: 5

Shubham Srivastava
Shubham Srivastava

Reputation: 1877

A typedef can be used to specify a function signature that we want specific functions to match. A function signature is defined by a function’s parameters (including their types). The return type is not a part of the function signature.

typedef function_name(parameters)

A variable of typedef can point to any function having the same signature as typedef.

typedef  var_name = function_name

One declared a type while other assigns it to a typedef variable

https://dart.dev/guides/language/language-tour#typedefs

Upvotes: 0

Related Questions