Wiki

Dynamic Type

As well as (explicit and inferred) static typing, Cobra supports dynamic typing (or late binding) where type determination is deferred to runtime rather than being specified at coding/compile time.

Any kind of object, whether primitive, value, reference (or nil), can be used where a dynamic (dynamic?) type is expected.

Variables, fields, parameters and return types can be explicitly specified as dynamically-typed using the cobra keyword dynamic.

If a type is not provided (either as an explicit type clause or as an initialiser expression) on an (otherwise untyped) object variable, method argument or property, the type defaults to dynamic (dynamic?).

class X
    var x
    # no explicit type given so field x is default typed as dynamic

    var y = 99 # initialser expression so type inferred from that (int)
    var z as String?  # explicit type specified - nilable String

    cue init(x)  # arg type x here is also dynamic
        .x = x

    def echo
        print 'x=[.x] x.getType=[.x.getType]'

Local variables are not defaulted to dynamic type but instead are statically typed with the type inferred from the righthand side of an (assignment) expression. Of course, if the right hand expression is of type "dynamic" then so is the variable.

  i = 0 # i inferred as int (from value 0)
  s = 'aString' # s inferred as type String 

  s1 as dynamic # local variable explicitly typed as dynamic/late bound
  s1 = s   # works  - s1 bound at runtime to same type as s 

If need be expressions can be cast to dynamic to preserve late binding semantics with dynamic fields/variables

    var x
....
    .x = .lookItUp(42) to dynamic  

Operations on dynamic expressions are late bound like in Smalltalk and Python.

    def (x, y) as dynamic
        return (x + y)

See also: TypesOverview, LanguageTopics