Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function within a function in Java [duplicate]

Tags:

java

Is it possible to define a function within a function in Java? I am trying to do something like:

public static boolean fun1() {   static void fun2()   {      body of function.   }   fun();   return returnValue; } 

but I am getting error Illegal start of expression.

like image 907
Harshveer Singh Avatar asked Aug 17 '11 17:08

Harshveer Singh


People also ask

Can you have a function within a function in Java?

Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile.

Can a function return another function in Java?

You can't technically return a function, but you can return the instances of classes representing functions, in your case UnaryFunction .

Can a function have another function?

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.

How do you call a method inside a method in Java?

Call a Method Inside main , call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"


1 Answers

The reason you cannot do this is that functions must be methods attached to a class. Unlike JavaScript and similar languages, functions are not a data type. There is a movement to make them into one to support closures in Java (hopefully in Java 8), but as of Java 6 and 7, it's not supported. If you wanted to do something similar, you could do this:

interface MyFun {     void fun2(); }  public static boolean fun1() {   MyFun fun2 = new MyFun() {       public void fun2() {           //....       }   };   fun2.fun2();   return returnValue; } 
like image 131
Mike Thomsen Avatar answered Oct 07 '22 22:10

Mike Thomsen