3. Implementation/Java

Functions as First-Class Values (1등 시민으로서의 함수)

SSKK 2016. 7. 21. 13:23

What is Functions as First-Class Values?


This is translated as "1등 시민으로서의 함수" in Korean. (Why is this translated like that?)

First class? 1등 시민? 


First-class (en-en dictionary)

: If you describe something or someone as first-classyou mean that they are extremely good and of the highest quality.


A class of this term does not mean the class of java. It seems that to distinguish class word from general java class "시민" might be used. 

But it causes me to understand it more confused. 


Anyway, return to the subject.


In Java, we are accustomed to passing objects and primitive values to methods, returning them from methods, and assigning them to variables. This means that objects and primitives are first-class values in Java. 


Java cannot declare any function without a class. Instead java only has methods.

But methods aren't first-class in Java.


You can't pass a method as an argument to another methods, return a method from a method, or assign a method as a value to a variable.


However, most anonymous inner classes are effectively function "wrappers".


Many Java methods take an instance of an interface that declares one method. 



package functions;
import java.awt.*;
import java.awt.event.*;
class HelloButtonApp2 {
 private final Button button = new Button();
 public HelloButtonApp2() {
 button.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 System.out.println("Hello There: event received: " + e);
 }
 });
 }
}


Let's introduce a abstraction for all these "function objects"!.



package functions;
public interface Function1Void( <A >) {
 void apply(A a);
}


And let's try to use Function1Void like :


package functions;
import java.fawt.*;
import java.fawt.event.*;
class FunctionalHelloButtonApp {
 private final Button button = new Button();
 public FunctionalHelloButtonApp() {
 button.addActionListener(new Function1Void <ActionEvent >() { // 1
 public void apply(ActionEvent e) { // 2
 System.out.println("Hello There: event received: "+e);
 }
 });
 }
}

Abstraction callback function is great but instead of using this, lambda approach on Java 8 is better. 


Refer : Functional Programming for Java Developers by Dean Wampler