Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obscure Dart syntax

Tags:

dart

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?

like image 769
Nathaniel Johnson Avatar asked Dec 08 '22 11:12

Nathaniel Johnson


2 Answers

(_) 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.

like image 84
Dennis Kaselow Avatar answered Jan 18 '23 09:01

Dennis Kaselow


(_) => 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 : (_) => _.

like image 40
Alexandre Ardhuin Avatar answered Jan 18 '23 09:01

Alexandre Ardhuin