Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of C# anonymous methods in Java?

In C# you can define delegates anonymously (even though they are nothing more than syntactic sugar). For example, I can do this:

public string DoSomething(Func<string, string> someDelegate) {      // Do something involving someDelegate(string s) }   DoSomething(delegate(string s){ return s += "asd"; }); DoSomething(delegate(string s){ return s.Reverse(); }); 

Is it possible to pass code like this in Java? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics).

like image 218
Callum Rogers Avatar asked Aug 27 '09 10:08

Callum Rogers


People also ask

What is equivalent to classes in C?

There is nothing equivalent to classes . Its a totally different paradigm. You can use structures in C. Have to code accordingly to make structures do the job.

What is the equivalent of new in C?

There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.

Is C similar to C+?

C++ is a superset of C, so both languages have similar syntax, code structure, and compilation. Almost all of C's keywords and operators are used in C++ and do the same thing. C and C++ both use the top-down execution flow and allow procedural and functional programming.

What is delete in C?

delete keyword in C++ Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.


1 Answers

Pre Java 8:

The closest Java has to delegates are single method interfaces. You could use an anonymous inner class.

interface StringFunc {    String func(String s); }  void doSomething(StringFunc funk) {    System.out.println(funk.func("whatever")); }  doSomething(new StringFunc() {       public String func(String s) {            return s + "asd";       }    });   doSomething(new StringFunc() {       public String func(String s) {            return new StringBuffer(s).reverse().toString();       }    }); 

Java 8 and above:

Java 8 adds lambda expressions to the language.

    doSomething((t) -> t + "asd");     doSomething((t) -> new StringBuilder(t).reverse().toString()); 
like image 117
Michael Lloyd Lee mlk Avatar answered Sep 23 '22 17:09

Michael Lloyd Lee mlk