Boo is a statically typed language.
Static typing is about the ability to type check a program for type correctness.
Static typing is about being able to deliver better runtime performance.
Static typing is not about putting the burden of declaring types on the programmer as most mainstream languages do.
The mechanism that frees the programmer from having to babysit the compiler is called type inference.
Type inference means you don't have to worry about declaring types everywhere just to make the compiler happy. Type inference means you can be productive without giving up the safety net of the type system nor sacrificing performance.
Boo's type inference kicks in for newly declared variables and fields, properties, arrays, for statement variables, overriden methods, method return types and generators.
Assignments can be used to introduce new variables in the current scope. The type for the new variable will be inferred from the expression on the right.
Only the first assignment to a variable is taken into account by the type inference mechanism.
The following program is illegal:
Declare the new field _name and initialize it with an empty string. The type of the field will be string.
When a property does not declare a type it is inferred from its getter.
In this case the type of the Answer property will be inferred as int.
The type of an array is inferred as the least generic type that could safely hold all of its enclosing elements.
For statement variables
This works even when with unpacking:
When overriding a method, it is not necessary to declare its return type since it can be safely inferred from its super method.
Method return types
The return type of a method will the most generic type among the types of the expressions used in return statements.
When a method does not declare a return type and includes no return statements it will be typed System.Void.
A Word of Caution About Interfaces
When implementing interfaces it's important to explicitliy declare the signature of a method, property or event. The compiler will look only for exact matches.
In the example below the class will be considered abstract since it does not provide an implementation with the correct signature:
Ok. So where do I have to declare types then?
Let's say when.
- when the compiler as it exists today can't do it for you. Ex: parameter types, recursive and mutually recursive method/property/field definitions, return for abstract and interface methods, for untyped containers, properties with a only set defined
- when you don't want to express what the compiler thinks you do:
- when you want to access a member not exposed by the type assigned to an expression:
- when you want to use Duck Typing: