Variable declaration specifies the name of the variable that would be stored in the memory and memory can be accessed further with this name of variable. There are three types of scope for Scala variable.
- Method Parameters.
- Local Variables.
Let’s discuss each of them in detail.
We can access these kind of variables from every method in the object & from outside the object if we declared them with the right access modifiers.A field may be mutable or immutable, they can define them using ‘var’ or ‘val’.
Value of y : 7.0 Value of x : 10.3
Above example shows disp class is created with field variables x and y. These variables can be accessed inside a method and invoked this from an object by creating reference.Hence below is the output obtained.
We use these variables when we want to pass a value inside the method when we call it. They can be accessed inside the method and outside method if there is a reference to the object from outside the method. these variables are always mutable Using with ‘val’ keyword.
Area is: 50
Above Example shows
rect class is created with
mult method accepting two method parameter variables s1 and s2. Area object is created and rect method is invoking by passing the values to variables s1 and s2.Hence below is the output obtained.
These type of variables are declared inside a method and are accessible within it only.Using ‘var’ & ‘val’ keywords, these variables can be both mutable & immutable.
Area is: 240
Above example shows class Area having local variables s1, s2 & s inside method mult.These variables are not accessible outside the method.Hence the output obtained is below.
- Controlling Method Scope In Scala
- Variables in Scala
- Scala Tutorial – Learn Scala with Step By Step Guide
- Scala short <(x: Short): Boolean
- Scala short <(x: Char): Boolean
- Scala Extractors
- Scala | Partially Applied functions
- Scala String indexOf(String str) method with example
- Scala String contentEquals() method with example
- Scala Keywords
- Scala Int /(x: Int) method with example
- Scala Int /(x: Short) method with example
- Program to print Java Set of characters in Scala
- Scala Map size() method with example
- Scala SortedMap addString() method with a start, a separator and an end with example
- Scala Iterator addString() method with example
- Scala String substring(int beginIndex, int endIndex) method with example
- Scala | Functions Call-by-Name
- Program to convert Java list to an iterator in Scala
- Scala Set &() method with example