Version 1 (modified by hopscc, 11 years ago)


Nilable Types

Cobra forces specification of variables that may be allowed to contain nil. This is done by typing the variable as a nilable Type which is any typeName with a '?' suffix


    str as String = "Mystring"    # str can only have a String value
    strN as String?               # strN may have a String value OR nil

    lazyType as Type?             # Type OR nil

nilable Typing can be applied to anything that can be Typed ( variables, Args, parameters, returnTypes)

    def sendWelcome(cust as Customer, referral as Customer?) 
        # will not accept nil for `cust`
        # will accept nil for `referral` 

Casting to and From nilable Types

Sometimes it is necessary to cast an existing typed variable to a nilable type
( e.g for receiving results of a library call) or
to cast a nilable type to its non nilable type (when you've ascertained its not nil and the receiver only takes a non nilable type)

There is a shorthand for both of these

Casting to a nilable version of an existing type

<variable> to ?

Casting away from nilable version

<variable> to !


    s as String = 'a string'
    sn = s to ?    # sn is String?
    assert sn
    s1 = sn to !   # s1 is String - may not get nil

nil and not nil detection and coalesce

You can explicitly test for nil or not nil values using normal conditionals ( true is non-nil)

    s as String = 'sss'
    assert s
    if s
        print 's not nil'
    sn as String? = nil
    assert not sn
    if not sn
       print 'sn is nil'

Nil test and assign or non nil test and process can be done using 'nil coalescing'

? coalesce if nil.

! execute if not nil.

    stuff as String? = nil
    stuff = stuff ? defaultStuff  # coalesce nil
    # equivalent to  stuff = if (not stuff, defaultStuff, stuff)
    # or 
    # if not stuff
    #    stuff = defaultStuff
    assert stuff == defaultStuff

    def doSomething(input as String)
        if input  # detect not nil
            print 'Received some input.'

        i as int? = input ! .parse(input)  # execute non-nil
        # equiv to 
        #    i = if(input, .parse(input), input)

	# or alternatively
	# input = input ? '0'
	# i as int = .parse(input)