Tuesday 26 September 2017

2)Scala Declare Variables And Types

Scala Declare Variables And Types
Variables are the placeholders for values in scala

There are two types of variables:

  1. Immutable variables
  2. 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 = 5
Note:
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:

  1. Any is the supertype of all types, also called the top type.
  2. 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

Fundamentals of Python programming

Fundamentals of Python programming: Following below are the fundamental constructs of Python programming: Python Data types Python...