Recently I've run into code like this:
var myVariable: variableKind = _
It seems to be a way to assign null
to myVariable
.
Can anyone explain the rationale behind _
in this case?
What are the differences between assigning _
and null
to a variable?
An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things.
The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8.
Python automatically stores the value of the last expression in the interpreter to a particular variable called "_." You can also assign these value to another variable if you want.
__var__ : double leading and trailing underscore variables (at least two leading and trailing underscores). Also called dunders. This naming convention is used by python to define variables internally. Avoid using this convention to prevent name conflicts that could arise with python updates.
It initialises the variable with it's default value - this value depends on the type. For numeric types, this is zero
, false
for booleans, ()
for Unit
and null for types extending AnyRef
.
The value assigned depends on the declared type. If your "variableKind" extends AnyRef, the default value (for any object) is null. For numeric types it's zero, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With