Auto keyword and when to use it
QueenSvetlana
svetlanalilyrosemond at gmail.com
Tue Aug 21 21:37:00 UTC 2018
On Tuesday, 21 August 2018 at 18:44:15 UTC, Jim Balter wrote:
> Python is not statically typed; D is. Why are you talking about
> Python? You asked whether D's auto is like C#'s var ... it is,
> but it doesn't have C#'s pointless restriction of not being
> allowed for non-local declarations.
I think you misunderstood my point. Let me elaborate. In Python a
type could change at anytime, for example:
number = 1
In Python the variable number will be treated as an int, but at
any point in my code, that could change, in Python this is legal:
number = "one"
The code will compile and run. Now Python introduced type hints
to tell the reader how to treat the variable.
The problem with the code is, when you have a class, take my
Person example, a person will obviously have a first and last
name, which should be strings, now without validation I can pass
ints to those variables, which is undesirable. I would need a
private function to check the types passed and reject it if they
aren't strings, in addition to if the string is blank or contains
foreign characters.
I had a misunderstanding about the keyword auto because I
wrongfully believed that it made the code like Python, and for
that I apologize. I thought you were allowed to make class
variables auto, so for example:
class Person{
auto firstName
auto lastName
}
If this was allowed, when I create my person object, I can pass
ints to firstName and lastName, which is obviously undesirable. I
would need to check what value types were passed and reject them
if they aren't strings.
As pointed out in the answers above, this isn't legal, which
means, there is no need to check anything, it won't compile.
More information about the Digitalmars-d-learn
mailing list