Re: [Vala] Using 'as' for casting?



A third type of cast.

There is a way to use generics to get covariant types wherever you
want and do away with most 'as' dynamic casts. The effect is the same
as static (Type) casts but you're either all right or all wrong for a
class. I'm not sure if it's a good practice all the time but there
might be a place for it. I used this for a little while and then went
back to 'as' casts. Even if the type is generic the variable/function
name isn't e.g. I'd rather call a Child a 'child' than a generic
'person' or 'patient'.

class Person {}
class Child : Person
{
    public Toy favorite_toy { get; set; }
}

class Doctor <PT>
{
    // Every doctor has a next patient.
    PT next_patient () { ... }

    // Doctors are specialized when they see a patient.
    abstract void see_next_patient ();
}

class Pediatrician : Doctor <Child>
{
    override void see_next_patient ()
    {
        // c is a Child. No 'as' cast needed thanks to the type parameter.
        var c = next_patient ();
        talk_about (c.favorite_toy ());
    }
}



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]