Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are function typedefs / function-type aliases in Dart?

Tags:

typedef

dart

I have read the description, and I understand that it is a function-type alias.

  • A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types. A typedef retains type information when a function type is assigned to a variable.

  • http://www.dartlang.org/docs/spec/latest/dart-language-specification.html#kix.yyd520hand9j

But how do I use it? Why declaring fields with a function-type? When do I use it? What problem does it solve?

I think I need one or two real code examples.

like image 973
Gero Avatar asked Sep 22 '12 16:09

Gero


People also ask

What is function-type in Dart?

There are four main types of user define functions (based on arguments and return type). Function with no arguments and no return type. Function with arguments and no return type. Function with no arguments and return type. Function with arguments and with return type.

What is the function of the typedef?

A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.

Is Dart type safe?

The Dart language is type safe: it uses a combination of static type checking and runtime checks to ensure that a variable's value always matches the variable's static type, sometimes referred to as sound typing.

How do you know what variable you are in Dart?

To check the type of a variable in Flutter and Dart, you can use the runtimeType property.


1 Answers

A common usage pattern of typedef in Dart is defining a callback interface. For example:

typedef void LoggerOutputFunction(String msg);  class Logger {   LoggerOutputFunction out;   Logger() {     out = print;   }   void log(String msg) {     out(msg);   } }  void timestampLoggerOutputFunction(String msg) {   String timeStamp = new Date.now().toString();   print('${timeStamp}: $msg'); }  void main() {   Logger l = new Logger();   l.log('Hello World');   l.out = timestampLoggerOutputFunction;   l.log('Hello World'); } 

Running the above sample yields the following output:

Hello World
2012-09-22 10:19:15.139: Hello World

The typedef line says that LoggerOutputFunction takes a String parameter and returns void.

timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.

Let me know if you need another example.

like image 146
Cutch Avatar answered Sep 19 '22 15:09

Cutch