Part II — Intermediate Development · Chapter 7 · Lesson 2 of 7 · 9 min read
Lesson 2: Inference, Compatibility, and Gradual Adoption
Lesson level: Intermediate
Purpose: Understand how PeaLang derives types from context, decides whether values satisfy declared contracts, and strengthens existing programs without requiring an all-at-once migration.
Learning objectives
By the end of this lesson, you should be able to:
- explain local type inference and its limits;
- distinguish inferred, declared, and unknown type information;
- reason about compatibility for assignments, calls, and returns;
- identify safe and unsafe widening or narrowing;
- interpret diagnostics caused by conflicting constraints;
- add annotations incrementally without changing behavior;
- preserve untyped callers while strengthening public contracts; and
- combine semantic checks with runtime validation and tests.
2.1 Why inference matters
Annotations communicate contracts explicitly, but repeating an obvious type at every local binding can obscure the program’s real logic. Type inference lets semantic analysis derive useful information from literals, expressions, assignments, function signatures, and control flow.
let quantity = 3 let unit_price = 12.5 let subtotal = quantity * unit_price
The initializer establishes useful type information for each binding without requiring a written annotation. The checker can then analyze later operations against those inferred types.
Design principle. Prefer explicit contracts at important boundaries and inference for obvious implementation details.
2.2 Sources of inferred information
- Literals: integers, floating-point numbers, strings, booleans, null, and collection forms provide initial evidence.
- Expressions: operators constrain the types of operands and results.
- Assignments: later writes must remain compatible with the binding’s contract.
- Function calls: parameter contracts constrain arguments, and return contracts determine call-result types.
- Branches: the checker combines information from reachable paths.
- Collections: elements or entries contribute constraints to the collection type.
- Imported declarations: module interfaces provide types without exposing implementation details.
Inference should remain explainable. If a type depends on distant or conflicting evidence, add an annotation at the point where the intended contract becomes meaningful.
2.3 Declared types constrain inference
An explicit annotation is not a suggestion for the checker to replace. It states the intended contract, and the initializer must be compatible with it.
let retries: Int = 3 let label: String = "pending" let enabled: Bool = true
If an initializer conflicts with the annotation, investigate whether the data, annotation, or domain model is wrong. Do not broaden the annotation merely because the current expression is inconvenient.
2.4 Compatibility in assignments
Assignment is valid when the new value satisfies the existing binding contract. An inferred binding also establishes expectations from its initializer.
let attempts = 0 attempts += 1 attempts = "one" // incompatible
Compatibility prevents a name from changing meaning unpredictably. A variable called attempts should not begin as a counter and later become a message.
2.5 Compatibility in function calls
Each argument is checked against its corresponding parameter contract.
function repeat(message: String, count: Int) -> String { return std.string.repeat(message, count) } let banner = repeat("Ready", 3) let invalid = repeat(3, "Ready") // both arguments conflict
Named parameters, defaults, and higher-order uses introduce additional constraints, but the central question remains: can the supplied value safely satisfy the parameter’s declared role?
2.6 Compatibility in return paths
Every reachable normal return must satisfy the function’s result contract.
function response_minutes(priority: String) -> Int { if priority == "critical" { return 15 } if priority == "high" { return 60 } return 480 }
A branch returning "unknown" would violate the contract. If failure is a legitimate outcome, model it explicitly rather than mixing an error sentinel into the success type.
2.7 Branch joins and mixed paths
When control flow can produce different values for one binding, the checker must find a compatible result for every reachable path.
let label = "standard" if security_relevant { label = "critical" } else { label = "ordinary" }
Both paths preserve the string contract. If one path assigned a number, the join would expose a conflict. Use separate variables or a deliberate union-like model only when the domain truly permits multiple forms.
2.8 Widening and narrowing
Widening accepts a broader set of values; narrowing establishes a more specific contract. Widening can improve interoperability when it reflects the real domain, but it also removes guarantees. Narrowing can improve safety only when supported by validation, flow evidence, or an explicit conversion.
Do not confuse numeric compatibility with arbitrary coercion. A checker may permit documented compatible numeric use while still rejecting strings, booleans, or null. Never assume that a type mismatch will be repaired automatically at runtime.
2.9 Unknown information and gradual boundaries
Gradual typing must represent places where complete static knowledge is unavailable: unannotated legacy functions, dynamically shaped host data, optional integrations, or values produced across an untyped boundary. Unknown information should be contained rather than allowed to spread silently through the project.
Place an explicit typed adapter around an uncertain boundary:
- receive the external or legacy value;
- validate its portable shape and business constraints;
- convert it into a typed internal representation;
- call strongly typed domain functions; and
- validate or convert the result before returning it.
This adapter pattern lets old and new code coexist while making uncertainty visible at a small number of locations.
2.10 A staged adoption plan
- Establish behavior. Format, check, and test the current program before changing contracts.
- Map boundaries. Identify exports, imports, host entry points, file or network data, and shared domain functions.
- Annotate stable interfaces. Start with functions whose inputs and outputs are already well understood.
- Contain dynamic data. Add validation and conversion adapters.
- Resolve high-value diagnostics. Fix real incompatibilities before cosmetic gaps.
- Strengthen internal models. Add precise types to domain values and important collections.
- Remove temporary escape hatches. Replace broad or unknown contracts as evidence improves.
- Enforce the new baseline. Add semantic checks to review and automation.
Migrate one coherent slice at a time. A slice might be one exported function and its direct helpers, not an arbitrary number of files.
2.11 Preserving compatibility for existing callers
Adding annotations can reveal that callers already pass inconsistent values. Decide whether the existing behavior is valid compatibility or an undocumented defect.
- If the old input is legitimate, model and validate it explicitly.
- If it is deprecated, keep a narrow conversion adapter and emit a migration diagnostic or note.
- If it is unsafe or accidental, reject it and document the required correction.
- If a return contract changes, provide a transition path rather than silently changing its shape.
Compatibility is a product decision, not permission to accept every historic value forever.
2.12 Reading inference diagnostics
A diagnostic may originate where incompatible evidence meets rather than where the wrong value was created. Trace the value backward to its declaration, branch, call, or boundary.
Use this sequence:
- read the expected and actual types;
- identify which contract supplied the expectation;
- find where the actual value was inferred;
- inspect all relevant branches and callers;
- decide the intended domain contract;
- fix the narrowest incorrect producer or declaration; and
- rerun semantic checks and behavior tests.
When many diagnostics appear after one annotation, group them by root cause. A single imprecise boundary or inconsistent return path can create several downstream messages.
2.13 Inference does not replace design
The checker can derive relationships present in the program, but it cannot invent missing domain meaning. A number may represent currency, percentage, count, duration, or identifier. Clear names, documented units, structured types, and runtime rules remain necessary.
Inference should reduce repetition, not hide intent. Add an annotation when it marks an architectural boundary, prevents a dangerous ambiguity, or makes a contract easier to review.
2.14 Worked migration example
Consider an untyped pricing function used by both a command-line script and a host application:
function calculate_total(quantity, unit_price, discount) { return quantity * unit_price - discount }
A safe migration proceeds as follows:
- Capture tests for ordinary, zero, boundary, and invalid values.
- Confirm that the host validates portable input before the call.
- Add the intended signature: quantity: Int, unit_price: Float, discount: Float, and -> Float.
- Run semantic checks and inspect every existing caller.
- Keep a conversion adapter only for callers whose supported input format differs.
- Rerun behavior tests and compare results with the baseline.
The annotation phase should not change pricing policy. It should make the existing contract explicit and expose unsupported variations.
2.15 Common mistakes
- Annotating everything immediately. Large migrations produce noisy diagnostics and obscure root causes.
- Trusting inference across an external boundary. External data still requires validation.
- Broadening types to suppress errors. This can erase useful guarantees.
- Adding arbitrary conversions. A conversion needs a documented domain meaning.
- Assuming compatible means identical. Compatibility follows defined language rules, not textual equality alone.
- Changing behavior during annotation. Separate contract migration from feature changes.
- Ignoring untyped callers. Existing integrations need an explicit compatibility plan.
- Leaving temporary unknowns permanent. Track and reduce uncertainty over time.
- Relying on semantic checks alone. Preserve tests and runtime validation.
2.16 Guided practice
- Infer the types of bindings initialized with an integer, float, string, boolean, list, and map.
- Identify the conflict in a binding initialized with a number and later assigned text.
- Trace a function-call mismatch back to the argument producer.
- Review a function whose branches return different value kinds.
- Decide whether a proposed wider type reflects the domain or merely hides a defect.
- Design a typed adapter around an untyped portable map.
- Choose one module boundary where explicit annotations provide more value than local annotations.
- Write a migration order for three dependent functions.
2.17 Hands-on lab: Gradually type the pricing rules library
Scenario. Strengthen the Chapter 4 pricing library while preserving its established outputs and untyped host-facing input format.
Requirements
- Record the current public functions, callers, tests, and portable inputs.
- Run the existing format, source, semantic, and behavior checks as a baseline.
- Add parameter and return annotations to one exported calculation path.
- Allow inference for obvious local intermediate values.
- Add an adapter that validates and converts the host-provided map.
- Introduce deliberate assignment, call, and return mismatches; record their diagnostics.
- Correct the mismatches without weakening valid domain contracts.
- Check every branch that contributes to the final result.
- Verify that existing valid callers receive unchanged portable outputs.
- Document deprecated or rejected caller patterns.
Required test groups: ordinary pricing, zero quantity, exact discount boundary, invalid negative values, missing fields, incompatible field types, legacy caller format, and typed direct calls.
Acceptance criteria. Semantic checks pass after deliberate defects are removed; all valid baseline tests remain unchanged; invalid boundary data is rejected explicitly; uncertainty is confined to the adapter; and the migration note describes compatibility decisions.
2.18 Review questions
- What sources of evidence can type inference use?
- Why does an explicit annotation constrain rather than merely describe an initializer?
- Where is compatibility checked in assignments, calls, and returns?
- Why can one inconsistent branch affect the type of a later expression?
- What is the risk of widening a contract only to remove a diagnostic?
- How should uncertain host data enter typed domain code?
- Why should gradual adoption begin at stable boundaries?
- How can existing untyped callers be supported temporarily?
- Why must annotation changes be separated from behavior changes?
- What evidence shows that a gradual migration preserved compatibility?
2.19 Applied challenge
Select one earlier checkpoint project and create a three-stage typing roadmap. For each stage, name the functions and boundaries to strengthen, the diagnostics expected, the compatibility risks, the runtime validators retained, and the tests that prove unchanged behavior. Implement the first stage and report any defect exposed by inference or compatibility checking.
Lesson summary
Type inference reduces repetitive annotations by deriving information from literals, expressions, assignments, calls, branches, and interfaces. Compatibility rules keep assignments, arguments, and returns aligned with their contracts. Gradual adoption succeeds when teams establish a behavioral baseline, type stable boundaries first, contain uncertain data behind validated adapters, resolve diagnostics by root cause, and preserve tests and supported callers.
Lesson status: Ready for review.
Next: Chapter 7, Lesson 3 — Generics and Substitution.