Introduction to Type Inference

Although you can explicitly declare the type of a local variable, you don't have to:

# the long way:
i as int = 0

# the short, easy way:
i = 0

The type of the variable on the left is taken to be the type of the expression on the right.

This also works for object variables:

class Person

    var _name = ''  # typed as String
    var _age = 0    # typed as int

If the inferred type is not suitable, perhaps because you need a more general type, you can provide one explicitly or even typecast the right-hand side:

class Person

    var _name = '' to dynamic
    var _age as int64 = 0

    def foo
        i = 0 to int64
        j as int64 = 0

Sometimes you want the variable to be typed as a base class because you may assign other things to it in the future:

    shape = Circle() to Shape

    share as Shape = Circle()


Type inference also occurs for the types of generic lists, sets and dictionaries:

    names = ['foo', 'bar']  # List<of String>
    numbers = {1, 2, 3}     # Set<of int>
    shapes = {'circle': Circle(), 'square': Square()}  # Dictionary<of String, Shape>

If Expressions

If-expressions are typed based on their two possible expression results:


Greatest Common Denominator


See Also

See also: TypesOverview, LanguageTopics