gtk3gnomevalagenie

Genie Vala Generics and Nullable Types


Simple question: In the following generic class, how should the generic type and contained types be defined so that they are nullable? The following will not compile.

class Pair? of G1, G2: Object

    _first:G1?
    _second:G2?

    construct()

        _first = null
        _second = null

    def insert( first:G1, second:G2 )

        _first = first
        _second = second

    def insert_first( value:G1 )

        _first = value

    def insert_second( value:G2 )

        _second = value

    def second():G2

        return _second

Usage:

var pair = new Pair() of string, string
pair = null

Solution

  • Due to the way Vala Generics work, generic parameters are always nullable.

    As long as you don't switch on --enable-experimental-non-null class variables are nullable as well, so your code simplifies to:

    [indent=4]
    class Pair of G1, G2: Object
    
        _first:G1
        _second:G2
    
        construct()
    
            _first = null
            _second = null
    
        def insert( first:G1, second:G2 )
    
            _first = first
            _second = second
    
        def insert_first( value:G1 )
    
            _first = value
    
        def insert_second( value:G2 )
    
            _second = value
    
        def second():G2
    
            return _second
    
    init
        var pair = new Pair of string, string
        pair = null
    

    When --enable-experimental-non-null is on, you have to be explicit in the type of the variable. I don't know how to write this in Genie, I tried this, but the compiler does not like it:

    init
        pair: Pair? of string, string = new Pair of string, string
        pair = null
    

    In Vala it's no problem:

    class Pair<G1,G2>: Object {
        private G1 first;
        private G2 second;
    
        public Pair () {
            first = null;
            second = null;
        }
    
        // ...
    }
    
    int main () {
        Pair<string, string>? pair = new Pair<string, string> ();
        pair = null;
        return 0;
    }