Dart (3.13) Module 7
Classes, constructors and enums interview questions
Interview questions on classes, constructors and enums: warm-ups, then what each harder question tests and how a good answer starts.
Warm-up questions
Short questions with short answers, each answered in full.
-
Fresher
What does an underscore in front of a Dart field mean, and which code can still read it?
Answered in the lesson Classes, objects, getters and privacy
-
Fresher
What can a factory constructor do that a generative constructor cannot?
Answered in the lesson Constructors: named, const, factory, redirecting
-
Fresher
In class P(final int x) and class P(int x), what is the difference?
-
Fresher
What does values.byName do when no enum value has the given name, and what would you use for text typed by a user?
-
Mid
When would you write a class with a call method instead of a closure?
Answered in the lesson Operator overloading, callable objects, metadata
Questions with model answers
What each question tests, the first step of a good answer and the follow-ups to expect.
-
Mid to senior
A shared package decides how to draw an item with if (item.runtimeType.toString() == 'Coupon'). The tests and the command-line tool work, and the production web build draws every coupon as a plain item. Explain the failure, and show how you would write the check and test it.
- What it tests
- Knowing that type names can be minified by the web compiler, that a type test with is is stable, and that a behaviour that depends on a kind belongs in a method or a type test.
- First step
- Print the runtimeType of a Coupon in the VM and in an optimized JavaScript build. Compare the two texts before you change any code.
- Follow-ups
-
- Why does the check pass in tests and fail on the web?
- What replaces the string comparison, and what does each choice cost?
- How do you make sure the web build is tested, not only the VM?
From the lesson Classes, objects, getters and privacy
Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.Opening the model answers with your pass…
Model answers open with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so the model answers can’t be opened at the moment. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A Profile class has String? nickname and a copyWith written as nickname: nickname ?? this.nickname. A screen calls profile.copyWith(nickname: null) to clear it, and the nickname stays. Explain why, and give two ways to fix the class, with their costs.
- What it tests
- Knowing that ?? cannot separate an omitted argument from an explicit null, and that a sentinel value, a wrapper or a clear flag fixes it with different trade-offs.
- First step
- Write down what the parameter holds when it is omitted and when null is passed, and check whether the expression can tell the two apart.
- Follow-ups
-
- Which values of the parameter are possible, and what does ?? do with each?
- How would a clear flag change the signature and the call sites?
- Why is a hand-written copyWith error-prone as the class grows?
From the lesson Classes, objects, getters and privacy
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A factory Stall.named(String name) keeps every stall it builds in a static map. A test for the stall called tea succeeds alone and fails when the whole suite runs, and a long-running service grows in memory by the day. Explain both symptoms and the changes you would make.
- What it tests
- Knowing that a static map outlives every test and every request, that cached objects are shared, and how to bound, reset or avoid the cache.
- First step
- Run the test alone and then after the tests that also ask for tea, and print identical for the two stalls. Then look at what the map holds after a day of different names.
- Follow-ups
-
- Why does one test change the result of another?
- What bounds the size of the map, and who removes entries?
- When is a cache the wrong design for an object like this?
From the lesson Constructors: named, const, factory, redirecting
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A Temperature class must refuse values below absolute zero, and must also offer a constant Temperature.freezing. Why can one public const constructor not do both, and what design gives you both?
- What it tests
- Knowing that a const constructor cannot run arbitrary checks, that asserts are not a run-time guarantee, and that a private const constructor plus a checking public constructor separates the two jobs.
- First step
- Try to write a throw in the initializer list of a const constructor and read the error. Then list who may call each constructor: your own constants, and your users with runtime values.
- Follow-ups
-
- What does an assert in a const initializer list guarantee, and when?
- How do you stop users from building an unchecked value?
- How does the factory parse reuse the checked path?
From the lesson Constructors: named, const, factory, redirecting
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
A team plans to move a published package of 150 classes to primary constructors with dart fix --apply. List what must be true before the release, what the change can and cannot affect for users, and how you would check it.
- What it tests
- Knowing that the feature changes the declaration and not the behaviour, that the lower SDK bound must rise to 3.13, that some constructors cannot convert, and how to verify with tests and the analyzer.
- First step
- Run the migration on a copy of one small package and compare the program's output before and after. Then read the pubspec's lower bound and the analyzer's report for the converted files under the old and the new constraint.
- Follow-ups
-
- Which classes will the fix leave alone, and why?
- What happens to users on an older SDK when the bound rises?
- Which tools and versions do you pin for a project with enums?
From the lesson Primary constructors in Dart 3.13
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
class Label(var String text, String suffix) has a field initializer first = text, an initializer list inList = text and a this block that runs text = text.toUpperCase() and prints text and suffix. Given Label('tea', '!'), state what each part sees, what is printed, and what the object holds afterwards.
- What it tests
- Knowing that initializers read the constructor parameter, that the this block reads the induced field, and that a parameter without a modifier is a parameter in both places.
- First step
- Write the three places in a row and, for each, mark whether the name refers to the parameter or to the field. Then trace the value of text and of the two initialized fields through the constructor.
- Follow-ups
-
- Why does suffix behave the same in the initializer list and the block?
- What would change if first were declared late?
- Why did the language choose two meanings for one name?
From the lesson Primary constructors in Dart 3.13
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A helpdesk app stores each ticket's Priority.index in a database column. Someone sorts the enum's values alphabetically to tidy the file. After the release, old tickets show the wrong priority and nothing crashed. Explain what happened, how you repair the data, and how you store the value from now on.
- What it tests
- Knowing that index is a position in the declaration, that reordering or inserting changes what a stored number means, and how to migrate and to store a name or an explicit code.
- First step
- Write down the old and the new order of the declaration, then read one stored number against both: the same integer names a different value. Check what the column holds for a ticket whose priority you know.
- Follow-ups
-
- Which edits to an enum change every index, and which leave them alone?
- How do you repair the rows that were already written after the release?
- What do you store instead, and what does the read side do with a value it does not know?
From the lesson Enhanced enums and dot shorthands
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A published package declares sdk: ^3.6.0. A contributor with a brand-new SDK installed wants dot shorthands such as .paid across the code. What does the analyzer say, what must change in the package, and who is affected by the change?
- What it tests
- Knowing that the language version comes from the pubspec's lower SDK bound, what the analyzer reports below 3.10, and that raising the bound limits which users can resolve the new release.
- First step
- Put the one-line shorthand file under the current constraint and run the analyzer, then under a constraint of 3.10.0 or higher. Compare the two reports before you think about releases.
- Follow-ups
-
- Why does a new local SDK not make the code legal under the old constraint?
- How does pub choose a version for a user whose SDK is older than the new bound?
- Is a shorthand worth a raised lower bound, and what else would you batch with it?
From the lesson Enhanced enums and dot shorthands
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A grid game stores visited cells in a Set<Cell>. Cell overrides == to compare row and column, and nothing else. Revisiting a cell is still counted as new, and contains returns false for a cell that was just added. Explain why, fix the class, and say what can still go wrong if a field of Cell is mutable.
- What it tests
- Knowing that hash-based collections look in a bucket chosen by hashCode before they call ==, that equal objects need equal hash codes, and that changing a field that hashCode uses moves an object away from its bucket.
- First step
- Build two equal cells, print a == b, then put one in a set and ask contains for the other. Then print both hash codes and compare them with what == says.
- Follow-ups
-
- Why does the set not simply call == on every element?
- How do you build the hash code, and from which fields?
- What happens to a stored cell whose row is changed afterwards?
From the lesson Operator overloading, callable objects, metadata
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
You maintain a package whose Client class should stop being created by new code, while old subclasses keep working for another release. You also want to hide a reset helper from users. Which annotations do you add, what do users see, and what does not change at run time?
- What it tests
- Knowing the Deprecated variants, that the analyzer reports them to code in other packages, that package:meta annotations such as visibleForTesting give warnings, and that annotations leave behaviour alone.
- First step
- List what you want to discourage, creating instances and using the helper, and match each to one annotation. Then put an app in a second package and read what the analyzer prints for it.
- Follow-ups
-
- Which variant fits creating an instance, and which fits extending?
- How would you check the wording that users will see?
- Does an annotation stop the code from running?
From the lesson Operator overloading, callable objects, metadata
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes