Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store function as class member variable

Tags:

dart

Is it possible in Dart to store a callback function with return and argument type information? It appears I can do the following:

class MyClass {
  void addCallback( callback( int ) )
  {
    _callback = callback;
  }

  var _callback;
}

But I thought it would be nice if _callback wasn't declared as var, and instead had information about its return and argument types. I couldn't find info on this in the docs, anyone know?

like image 326
rich.e Avatar asked Nov 05 '14 02:11

rich.e


People also ask

Can you store a function in a variable python?

In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.

How to define function in a class?

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.

What is member variable in c++?

In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).

What is a class function c++?

Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.


2 Answers

Dart 2 supports a function type syntax:

class MyClass {
  void addCallback( callback( int ) )
  {
    _callback = callback;
  }

  void Function(int) _callback;
}

The Effective Dart Design Guide states that this form is preferred over typedefs.

like image 78
notracs Avatar answered Nov 13 '22 04:11

notracs


You can typedef a Function signature like this:

typedef bool Filter(num x);

List<num> filterNumbers(List<num> numbers, Filter filter) {
  return numbers.where(filter).toList();
}

For more great information like this, check out this article: https://www.dartlang.org/articles/idiomatic-dart/

like image 38
montyr75 Avatar answered Nov 13 '22 06:11

montyr75