The idea of "code as data" is closely related to the concept of programming languages having first-class functions. See the Wikipedia article on this topic. In this other answer I talk about whether Java has first-class functions, but that article discusses some other issues as well.
The definition from the Wikipedia article (which cites Abelson & Sussman, Structure and Interpretation of Computer Programs, section 1.3) specifically mentions the following characteristics of functions that make them "first-class":
- can be passed as arguments to other functions
- can be returned as values from other functions
- can be assigned to variables
- can be stored in data structures
These are all things that you do with data. If you can do these same things with functions, then that's like treating "code as data."
If you look closely at how lambdas were added to the Java programming language, you'll see that a lambda is really converted to an instance of a functional interface. As such, it's an instance of some object, and therefore a descendant of class Object
, and like all objects in Java, it has equals(), hashCode(), getClass()
etc. methods, and references can be compared with ==
, and so forth. However, you are explicitly discouraged from relying on any of this. See my other answer for additional discussion. In practice, when you use lambdas in Java, it really feels like you're passing code as an argument, or assigning it to a variable. For example,
list.replaceAll(x -> doSomething(x));
Predicate<String> pred = s -> s.length() > 5;
You really end up not thinking about the fact that, under the covers, lambdas are objects that are instances of functional interfaces.