Learn or recall Dart with Koans. Part 2.
Variables and data types
In the previous part, we started to use Koans for Dart. We know what Koan is and how to run it. Now let’s use this superpower. In this article, we will load the full staffed pack of Koans to play with Dart’s variables.
Initial code
Let’s back to our previous project in FlutLab.io and copy/paste this code snippet into widget_test.dart:
You should see something like this:
A pretty good chunk of code! But don’t worry, we will crawl it one small step by another.
Now you have to run this test. Click at:
You will see build animation for a couple of seconds:
Which will end up with a failure report:
First Koan
You can quickly find the Koan responsible for this failure. Look for “Variables: explicit int variable”:
group('Variables:', () {
test('explicit int variable creation', () {
int pi = 3;
expect(___, pi);
});
...
What does this Koan teach us about? It says that we can create a variable of type int to save integer numbers. We stored value 3 to this variable with the name “pi”. expect function is inspecting the value of this variable. So we have to put “3” instead “___”:
group('Variables:', () {
test('explicit int variable creation', () {
int pi = 3;
expect(3, pi);
});
...
Now run Koans again. They should be green:
Meditation
Which interesting things we can see in this Koan also?
Notice this new construct: “group”. It is a very simple thing. It unites several test methods into one logical module. Also, it adds its name to all the failed test reports. So we saw “Variables: explicit int variable”, but not just “explicit int variable”.
Another good question can be asked: why we see all the green tests if we just resolved only one of them?
Look at the next line after previous Koan:
return; // remove this line to run the next test
Let’s follow the recommendation and remove this line completely.
Run the Koans!
And they are red again!
The answer is in using of return operator between tests. This operator interrupts the execution of the whole main function. So all the succeeding tests are just ignored.
All other Koans
It’s a very important moment on your path to enlightenment. Try to resolve the second and all following Koans by yourself.
Do shortstop after each Koan with “meditation” and think about your changes.
If you have problems with some Koans, check this “secret” code snippet. It contains resolved code for each Koan and a short upcoming note about its meaning:
Next steps
Stay tuned for the next part of Dart Koans. We’ll discover classes and objects.