Type Inference
You'll learn: How compilers can automatically figure out what type a variable should be without you explicitly declaring it.
The Core Idea
In earlier lessons, you learned about declaring variables with explicit types like int age = 25; or string name = "Alice";. Type inference is a compiler feature that lets you skip writing the type name — the compiler analyzes the value you assign and infers (deduces) the correct type automatically.
Think of it like this: if someone hands you an apple, you don't need them to say "This is a fruit" — you can see it's a fruit. Similarly, when you write x = 42, the compiler sees 42 is clearly an integer and assigns that type to x.
How It Works
Instead of writing:
int count = 10;
Many languages let you write:
var count = 10; // compiler infers count is an int
The compiler looks at 10, recognizes it as an integer literal, and makes count an integer variable. The variable is still strongly typed — you can't later assign count = "hello" because it's locked in as an integer. Type inference happens at compile time, not runtime.
This doesn't weaken type safety; it just reduces repetitive typing. The variable still has one fixed type throughout its lifetime.
Why It Matters
Type inference makes code cleaner and easier to maintain, especially when dealing with complex type names. The compiler does the bookkeeping for you while preserving all the safety guarantees of strong typing.
Key Takeaway: Type inference lets the compiler automatically determine a variable's type from its initial value, reducing verbosity while maintaining type safety.