Reputation: 121
I came across the following Dart code while reading about first where. I wanted to understand what exactly is happening in this code as this is some syntax I am not familiar with, particularly the "=>" symbols.
void main() {
final list = List<Book>.generate(10, (id) => Book(id));
Book findBook(int id) => list.firstWhere((book) => book.id == id);
print(findBook(2).name);
print(findBook(4).name);
print(findBook(6).name);
}
class Book {
final int id;
String get name => "Book$id";
Book(this.id);
}
Upvotes: 0
Views: 65
Reputation: 3594
This is what is called Syntaxic sugar
. It does not provide a special functionality but makes it easier for developer to write and read code.
In the cas of the =>
symbol, it is a shortcut for a function containing only a return statement. So those two definitions are exactly the same:
String main() {
return "Hello World"
}
String main() => "Hello World";
Note however, how the second one is way more readable.
So in your case if we unwrap everything your code would become:
void main() {
final list = List<Book>.generate(10, (id) {
return Book(id);
});
Book findBook(int id) {
return list.firstWhere((book) {
return book.id == id;
});
}
print(findBook(2).name);
print(findBook(4).name);
print(findBook(6).name);
}
class Book {
final int id;
String get name {
return "Book$id";
}
Book(this.id);
}
Upvotes: 3