Nathaniel Johnson
Nathaniel Johnson

Reputation: 4839

Obscure Dart syntax

While working through the the Dart Route library example for client side coding I came across this snippet.

 var router = new Router()
    ..addHandler(urls.one, showOne)
    ..addHandler(urls.two, showTwo)
    ..addHandler(urls.home, (_) => null)
    ..listen();

My question is how does (_) => null work? It seems to specify a function that returns a null value but what does (_) mean?

Upvotes: 4

Views: 391

Answers (3)

mezoni
mezoni

Reputation: 11200

I will try explain this by the example.

void main() {
  var helloFromTokyo = (name) => 'こんにちわ $name';
  var greet = new Greet();      
  greet.addGreet('London', helloFromLondon)
  ..addGreet('Tokyo', helloFromTokyo)  
  ..addGreet('Berlin', helloFromBerlin)
  ..addGreet('Mars', (_) => null)
  ..addGreet('Me', (name) => 'Privet, chuvak! You name is $name?')
  ..addGreet('Moon', null);

  greet.greet('Vasya Pupkin');
}

String helloFromLondon(String name) {
  return 'Hello, $name';
}

String helloFromBerlin(String name) {
  return 'Guten tag, $name';
}

class Greet {
  Map<String, Function> greets = new Map<String, Function>();

  Greet addGreet(String whence, String sayHello(String name)) {
    greets[whence] = sayHello;
    return this;
  }

  void greet(String name) {
    for(var whence in greets.keys) {
      var action = greets[whence];
      if(action == null) {
        print('From $whence: no reaction');
      } else {
        var result = action(name);
        if(result == null) {
          print('From $whence: silent');
        } else {
          print('From $whence: $result');
        }
      }
    }
  }
}

Output:

From London: Hello, Vasya Pupkin
From Tokyo: こんにちわ Vasya Pupkin
From Berlin: Guten tag, Vasya Pupkin
From Mars: silent
From Me: Privet, chuvak! You name is Vasya Pupkin?
From Moon: no reaction

Upvotes: 0

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76193

(_) => null means : a function that take one parameter named _ and returning null. It could be seen as a shortcut for (iDontCareVariable) => null.

A similar function with no parameter would be () => null.

A similar function with more parameters would be (_, __, ___) => null.

Note that _ is not a special syntax defined at langauge level. It is just a variable name that can be used inside the function body. As example : (_) => _.

Upvotes: 7

Dennis Kaselow
Dennis Kaselow

Reputation: 4551

(_) means it is a function with one parameter but you don't care about that parameter, so it's just named _. You could also write (ignoreMe) => null. The important thing here is, that there needs to be a function that accepts one parameter. What you do with it, is your thing.

Upvotes: 7

Related Questions