What are “first class” objects?

前端 未结 5 662
走了就别回头了
走了就别回头了 2020-11-22 16:50

When are objects or something else said to be \"first class\" in a given programming language, and why? In what do they differ from languages where they are not?

EDI

5条回答
  •  长发绾君心
    2020-11-22 17:23

    “First class” means you can operate on them in the usual manner. Most of the times, this just means you can pass these first-class citizens as arguments to functions, or return them from functions.

    This is self-evident for objects but not always so evident for functions, or even classes:

    void f(int n) { return n * 2; }
    
    void g(Action a, int n) { return a(n); }
    
    // Now call g and pass f:
    
    g(f, 10); // = 20
    

    This is an example in C# where functions actually aren't first-class objects. The above code therefore uses a small workaround (namely a generic delegate called Action<>) to pass a function as an argument. Other languages, such as Ruby, allow treating even classes and code blocks as normal variables (or in the case of Ruby, constants).

提交回复
热议问题