Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does it mean assign "_" to a field in scala?

Tags:

syntax

scala

I saw some scala code that assign "_" to a field of class, what does it mean ? Thanks

private var tk: TaggedKey = _
like image 826
zjffdu Avatar asked Apr 06 '12 08:04

zjffdu


People also ask

What does _ means in Scala?

Scala allows the use of underscores (denoted as '_') to be used as placeholders for one or more parameters. we can consider the underscore to something that needs to be filled in with a value. However, each parameter must appear only one time within the function literal.

What does case _ mean in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .

How do I assign a variable in Scala?

The multiple assignments can be possible in Scala in one line by using 'val' keyword with variable name separated by commas and the "=" sign with the value for the variable.

What does ::: mean in Scala?

:: - adds an element at the beginning of a list and returns a list with the added element. ::: - concatenates two lists and returns the concatenated list.


1 Answers

It means: assign default value. Default value is defined as null, 0 or false depending on the target type.

It is described in 4.2 Variable Declarations and Definitions of the The Scala Language Specification:

A variable definition var x : T = _ can appear only as a member of a template. It introduces a mutable field with type T and a default initial value. The default value depends on the type T as follows:

0 - if Tis Int or one of its subrange types,

0L - if Tis Long,

0.0f - if Tis Float,

0.0d - if Tis Double,

false - if Tis Boolean,

() - if Tis Unit,

null - for all other types T.

like image 118
Tomasz Nurkiewicz Avatar answered Sep 30 '22 11:09

Tomasz Nurkiewicz