if case instead of ! suffix

Using `if case` instead of a `!` suffix?


Have a look at the following code that shows different ways to access a possibly `null` value in a type-safe way in cases where a simple `foo?.` operator isn't possible:


    class Foo extends StatelessWidget {

      const Foo({super.key, this.bar});


      final String? bar;


      @override

      Widget build(BuildContext context) {

        return Column(

          children: [

            if (bar != null) Text(bar!),

            if (bar case var bar?) Text(bar),

            if (bar case final bar?) Text(bar),

            if (bar case String bar) Text(bar),

            if (bar case final String bar) Text(bar),

            if (bar case final String bar?) Text(bar),

          ],

        );

      }

    }


Most of you will probably use the `!= null` test in conjunction with the `!` operator.


We can however use an `if case` statement instead. The first variant is the shortest, but makes the newly introduced local `bar` variable mutable. Therefore, I'd prefer the second variant. That `?` as a shortcut for "make sure it isn't `null`" is a bit strange, though. Therefore, the third variant might be more explicit. Or again, if you like to declare your unmodifiable variables as `final`, use the fourth variant - which is quite verbose, though. Strangely enough, you can even combine this with the `?` suffix. 


The [equivalent Swift syntax](https://www.hackingwithswift.com/swift/5.7/if-let-shorthand) would be `if let bar { ... }`, BTW.


Do you already use this `if case` syntax?


Would you prefer this more verbose syntax just to omit the `!` cast or do you don't mind some `!` in your code base?


PS: You can also combine the `if case` with a "normal" condition using a `when` clause like so:


    if (bar case final bar? when bar.length.isOdd) ...


and, of course, the first `bar` can any be any complex expression.

Comments

Popular Posts