Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Lambda expressions, functional intfs and C# delegates  RSS feed

 
Claude Moore
Ranch Hand
Posts: 873
8
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks to me that with introduction of lambda expressions in Java it's now possible to use constructs that resemble C# delegates, a construct I personally missed a bit under some circumstances....
What do you think about ?
 
Paul Clapham
Sheriff
Posts: 22374
42
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like a possibility, maybe. But since I'm not an expert on either lambda-expressions (yet) or delegates, I can't quite see how in my 2 minutes of investigation. Would you like to take the idea a bit farther and put together an example?
 
Claude Moore
Ranch Hand
Posts: 873
8
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example:











In main method of Sample class, usage of Delegate interface seems *quite* a really assignment of a method of a class to a variable..
In C# we may write in a smarter syntax (IMHO)



Of course, mine it's only an idea..
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16006
87
Android IntelliJ IDE Java Scala Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, Java's functional interfaces are more or less equivalent to C# delegates. A delegate in C# is a function type.

During the development of the idea of lambda expressions in Java, Oracle's engineers have also thought about adding function types to Java. They decided not to do it because it would mean a big change in Java's type system, with lots of complicated consequences for other features of the type system.

I like the way they did it with single-method interfaces (now called functional interfaces). This makes lambda expressions fit very nicely in the existing Java language, and it means that you can use lambda expressions in a lot of existing code that was already using single-method interfaces. It would have been a lot less nice if the whole world would have to change their code to support lambda expressions.

Your example exactly shows how single-method interfaces are equivalent to C# delegates. Only the delegate(params); syntax doesn't exist in Java, you'd have to do delegate.exec(params); instead, as you noted. But maybe in the future that syntax could be added to Java.
 
Claude Moore
Ranch Hand
Posts: 873
8
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper, thanks for your reply. That's really enlightening under certain point of view.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!