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.
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.
You can't technically return a function, but you can return the instances of classes representing functions, in your case UnaryFunction .
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.
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!"
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; } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With