Scala Declare Variables And Types
Variables are the placeholders for values in scala
There are two types of variables:
1)Immutable variables:(non-changable)
To define immutable variable, we use the keyword val
Syntax:
If you try to make any changes to the Immutable varibale, scala will return an exception, says, reassignment not allow for val.
2)Mutable variables:
To declare a variable as mutable, we use the keyword var
Syntax:
Example:
Scala Types:
Following below are the scala types:
Note:
Example:
Other concepts related to varibles:
Lazy initialization:
Using Lazy initialization to delay the initialization of some variable until at the some point.
This can be done using lazy keyword
Syntax:
Declare a variable with no initialization:
Use the wildcard operator _ when defining our variable.
Example:
Variables are the placeholders for values in scala
There are two types of variables:
- Immutable variables
- Mutable variables
1)Immutable variables:(non-changable)
To define immutable variable, we use the keyword val
Syntax:
val <Name of varibale>: <Scala_type> = <Value literal>Example:
var number: Int = 5Note:
If you try to make any changes to the Immutable varibale, scala will return an exception, says, reassignment not allow for val.
2)Mutable variables:
To declare a variable as mutable, we use the keyword var
Syntax:
var <Name of variable> : <Scala_type>
Example:
Scala Types:
Following below are the scala types:
Note:
- Any is the supertype of all types, also called the top type.
- Any has two direct subclasses: AnyVal and AnyRef.
Example:
Other concepts related to varibles:
Lazy initialization:
Using Lazy initialization to delay the initialization of some variable until at the some point.
This can be done using lazy keyword
Syntax:
lazy val <Name of variable> = "literal value"Note:
- In the above we doesn't specify the type of string,
- The Scala compiler knew that it should be of type String. This is called type inference
Declare a variable with no initialization:
Use the wildcard operator _ when defining our variable.
Example:
var number: Int = _
number = 10
No comments:
Post a Comment