-2

I'm curious to know

  • Does Delegate exist in Scala Or Groovy like C# language or not ?

If your answer is no please explain

  • Why the modern languages like Groovy , Scala , ... does not support it like C# ?

Why Microsoft has accepted it, but others not ? So should not it be useful ?

Thanks

senia
  • 37,745
  • 4
  • 88
  • 129
HamedFathi
  • 3,667
  • 5
  • 32
  • 72

1 Answers1

4

What is a C# delegate? From MSDN Tutorial: A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object.

It is .CLR historic support for first-class functions. I.e. ability to use functions to be passed around just like any other value. From .NET 3.5 Func<> was added to the C# for this purpose.

Java can simulate this via anonymous inner classes. Scala has almost excellent first-class functions support:

val f = (x:Int) => x + 1

Groovy has first-class functions:

square = { it * it }

To be fair on the CLR delegates will work a bit faster than methods for JVM listed above. This is because JVM itself lacks support for a first-class functions and the only way to bring them back is to emulate this functionality.

Why Microsoft has accepted it, but others not ?

That's how historically things unrolled.

So should not it be useful ?

First-class functions are extremely useful in the functional programming.

vitalii
  • 3,335
  • 14
  • 18
  • Why the modern languages like Groovy , Scala , ... does not support it like C# ? Why Microsoft has accepted it, but others not ? – HamedFathi Jan 07 '14 at 19:06
  • `Looks like it is .CLR (limited) support for first-class functions.` Note that there are already lambdas (`Func<...>` with lambda syntax) in `C#`. Delegates exists mostly for backward compatibility. – senia Jan 07 '14 at 20:09
  • @vitalii,@senia : I thought the only way to implement lambda is Delegates like C# (Func<...> is delegate) - You say that there is no need to Delegate with lambda syntax ? In fact, any language that have lambda no need to Delegates ? no matter how lambda implemented in that language,with delegate concepts or not, Yes ? I just realized ?! – HamedFathi Jan 07 '14 at 20:41
  • @user3166171, you can emulate delegates even in the language that does not support lambdas, e.g. in Java you would define interface with one method and then you'll create anonymous inner class in place where you normally create a delegate. Comparator is a perfect example of this http://stackoverflow.com/a/2755450/1573825 – vitalii Jan 07 '14 at 20:56
  • @user3166171 Delegate is simply the name used in .Net for the concept generally known as "first-class function" or "closure". Other languages don't use _this name_, but they certainly support the concept. – Alexey Romanov Jan 08 '14 at 06:11