Skip to main content

Type Inference

Morph can automatically deduce the type of a variable from its assigned value, so you don't always need to write as <type>.


How It Works

The compiler examines the right-hand side of the assignment and infers the type:

x is 42;           // int
y is 3.14; // float
name is "Alice"; // string
flag is true; // bool

No as annotation is required when the type is unambiguous.


Inference Rules

Assigned ValueInferred Type
Integer literal (42)int
Float literal (3.14)float
String literal ("hi")string
true / falsebool
Function callReturn type of the function
Another variableType of that variable
another xType of x
move xType of x

When Inference Needs Help

Sometimes the compiler cannot determine the type. Use as in these cases:

// Ambiguous: is this int or float?
value is 0 as float; // explicitly float

// Uninitialized declaration
count as int; // type required, no value

Inference with Expressions

The compiler infers from expression results:

a is 5 + 10;     // int (int + int = int)
b is a * 2; // int
c is a * 2.0; // float (int * float = float)

Next Steps