delegates, lambdas and functions pitfall
Daniel Kozak via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Sep 5 05:29:36 PDT 2016
Dne 5.9.2016 v 14:15 dom via Digitalmars-d-learn napsal(a):
> I am about to write my own stupid and simple http client .. and i have
> added a callback function that has the received content as a parameter.
>
> class AsyncHttpGet
> {
> this(string host, ushort port, string path, void delegate(string)
> callback )
> { ... }
> }
>
> My first attempt was to write:
>
> auto f = new AsyncHttpGet("www.dprogramming.com", 80, "/index.php",
> (string content) => {
> ...
> });
>
> but this is does not work because my AsyncHttpGet takes a normal
> delegate and this => seems to add nothrow @nogc @safe to my delegate
> type.
>
> The correct syntax is only marginally differnt, but took me quite a
> while to figure out:
> ( the missing arrow )
>
> auto f = new AsyncHttpGet("www.dprogramming.com", 80, "/index.php",
> (string content)
> {
> ... // this is of type function
> });
>
> i noticed that delegates are "more powerful" than functions. once the
> passed function e.g. needs to capture a value from the outside it
> becomes a delegate type. I have also read that a delegate can contain
> a reference to a class method bound to an instance.
>
> int dummy = 0;
> auto f = new AsyncHttpGet("www.dprogramming.com", 80, "/index.php",
> (string content)
> {
> dummy = 1; // this is of type delegate
> });
>
> but what is the difference between a lambda (=>) and a
> functions/delegates?
> i think this is a major pitfall for newcomers, and should be adressed
> somehow.
(string content) => { } // this is delegate which returns another
delegates {} is shorthand here for (){}
when you use => syntax you can just return expression
(string content) => content; is same as (string content) { return content; }
More information about the Digitalmars-d-learn
mailing list