Nim: feature: have 'if' treat nil as false

Created on 27 Oct 2017  路  4Comments  路  Source: nim-lang/Nim

Although they're different types, allowing the 'if' construct to handle nil, as if it was false, will improve readability of code (even further).
I saw that feature in the cobra programming language (python for .net)
(they also treat 0 as false -- of course only in the 'if' clause)
if not found.is_nil means "if found is not nil", or "found is valid" but the wording is confusing
with this suggestion, the line becomes:
if found
Something to consider. It could be a good addition, and the drawbacks would be rare.

Feature

Most helpful comment

Oh sorry, forgot to tell you. You can already do this:

converter toBool(x: ref MyObject): bool = x != nil

var y: ref MyObject
if y:
  echo "nice"

All 4 comments

I don't see how a confusion of the basic types can aid in "readability".

@Araq
Can't speak for everyone, but I read these pieces of code differently due to the words order:

  • if found

Obvious one: "if something is found"

  • if found is not nil
    "if search result is not empty"
  • if not found.is_nil
    Tough one: my mind parses it right-to-left because not is a prefix operator. found.is_nil is equivalent to "search result is not valid". Then add not and get something like "if _not_(search result is _not_ valid)", i.e. "if search result is valid". Double negation breaks simplicity.

Although it is possible to get used to how it is now, X is not Y would be the best choice IMO.

Yeah ... well ... not gonna happen.

Oh sorry, forgot to tell you. You can already do this:

converter toBool(x: ref MyObject): bool = x != nil

var y: ref MyObject
if y:
  echo "nice"
Was this page helpful?
0 / 5 - 0 ratings