Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a underscore to a variable. What is the underscore doing?

Tags:

scala

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?

like image 324
Anthony Accioly Avatar asked Mar 12 '14 21:03

Anthony Accioly


People also ask

What is the use of underscore in 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.

What does an underscore after a variable mean?

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.

What is the use of _ in Python?

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.

What is __ variable __ in Python?

__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.


2 Answers

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.

like image 149
Lee Avatar answered Sep 28 '22 04:09

Lee


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.

like image 41
radumanolescu Avatar answered Sep 28 '22 03:09

radumanolescu