Scala – Classes & Objects

Scala – Classes & Objects ”; Previous Next This chapter takes you through how to use classes and objects in Scala programming. A class is a blueprint for objects. Once you define a class, you can create objects from the class blueprint with the keyword new. Through the object you can use all functionalities of the defined class. The following diagram demonstrates the class and object by taking an example of class student, which contains the member variables (name and roll no) and member methods (setName() and setRollNo()). Finally all are members of the class. Class is a blue print and objects are real here. In the following diagram, Student is a class and Harini, John, and Maria are the objects of Student class, those are having name and roll-number. Basic Class Following is a simple syntax to define a basic class in Scala. This class defines two variables x and y and a method: move, which does not return a value. Class variables are called, fields of the class and methods are called class methods. The class name works as a class constructor which can take a number of parameters. The above code defines two constructor arguments, xc and yc; they are both visible in the whole body of the class. Syntax class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x &plus; dx y = y &plus; dy println (“Point x location : ” + x); println (“Point y location : ” + y); } } As mentioned earlier in this chapter, you can create objects using a keyword new and then you can access class fields and methods as shown below in the example − Example import java.io._ class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x &plus; dx y = y &plus; dy println (“Point x location : ” &plus; x); println (“Point y location : ” &plus; y); } } object Demo { def main(args: Array[String]) { val pt = new Point(10, 20); // Move to a new location pt.move(10, 10); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Point x location : 20 Point y location : 30 Extending a Class You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor. Let us extend our above class and add one more class method. Example Let us take an example of two classes Point class (as same example as above) and Location class is inherited class using extends keyword. Such an ‘extends’ clause has two effects: it makes Location class inherit all non-private members from Point class, and it makes the type Location a subtype of the type Point class. So here the Point class is called superclass and the class Location is called subclass. Extending a class and inheriting all the features of a parent class is called inheritance but Scala allows the inheritance from just one class only. Note − Methods move() method in Point class and move() method in Location class do not override the corresponding definitions of move since they are different definitions (for example, the former take two arguments while the latter take three arguments). Try the following example program to implement inheritance. import java.io._ class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x &plus; dx y = y &plus; dy println (“Point x location : ” &plus; x); println (“Point y location : ” &plus; y); } } class Location(override val xc: Int, override val yc: Int, val zc :Int) extends Point(xc, yc){ var z: Int = zc def move(dx: Int, dy: Int, dz: Int) { x = x &plus; dx y = y &plus; dy z = z &plus; dz println (“Point x location : ” &plus; x); println (“Point y location : ” &plus; y); println (“Point z location : ” &plus; z); } } object Demo { def main(args: Array[String]) { val loc = new Location(10, 20, 15); // Move to a new location loc.move(10, 10, 5); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Point x location : 20 Point y location : 30 Point z location : 20 Implicit Classes Implicit classes allow implicit conversations with class’s primary constructor when the class is in scope. Implicit class is a class marked with ‘implicit’ keyword. This feature is introduced in Scala 2.10. Syntax − The following is the syntax for implicit classes. Here implicit class is always in the object scope where all method definitions are allowed because implicit class cannot be a top level class. Syntax object <object name> { implicit class <class name>(<Variable>: Data type) { def <method>(): Unit = } } Example Let us take an example of an implicit class named IntTimes with the method times(). It means the times () contain a loop transaction that will execute the given statement in number of times that we give. Let us assume the given statement is “4 times println (“Hello”)” means the println (“”Hello”) statement will execute 4 times. The following is the program for the given example. In this example two object classes are used (Run and Demo) so that we have to save those two classes in different files with their respective names as follows. Run.scala − Save the following program in Run.scala. object Run { implicit class IntTimes(x: Int) {

Scala – Access Modifiers

Scala – Access Modifiers ”; Previous Next This chapter takes you through the Scala access modifiers. Members of packages, classes or objects can be labeled with the access modifiers private and protected, and if we are not using either of these two keywords, then access will be assumed as public. These modifiers restrict accesses to the members to certain regions of code. To use an access modifier, you include its keyword in the definition of members of package, class or object as we will see in the following section. Private Members A private member is visible only inside the class or object that contains the member definition. Following is the example code snippet to explain Private member − Example class Outer { class Inner { private def f() { println(“f”) } class InnerMost { f() // OK } } (new Inner).f() // Error: f is not accessible } In Scala, the access (new Inner). f() is illegal because f is declared private in Inner and the access is not from within class Inner. By contrast, the first access to f in class Innermost is OK, because that access is contained in the body of class Inner. Java would permit both accesses because it lets an outer class access private members of its inner classes. Protected Members A protected member is only accessible from subclasses of the class in which the member is defined. Following is the example code snippet to explain protected member − Example package p { class Super { protected def f() { println(“f”) } } class Sub extends Super { f() } class Other { (new Super).f() // Error: f is not accessible } } The access to f in class Sub is OK because f is declared protected in ‘Super’ class and ‘Sub’ class is a subclass of Super. By contrast the access to f in ‘Other’ class is not permitted, because class ‘Other’ does not inherit from class ‘Super’. In Java, the latter access would be still permitted because ‘Other’ class is in the same package as ‘Sub’ class. Public Members Unlike private and protected members, it is not required to specify Public keyword for Public members. There is no explicit modifier for public members. Such members can be accessed from anywhere. Following is the example code snippet to explain public member − Example class Outer { class Inner { def f() { println(“f”) } class InnerMost { f() // OK } } (new Inner).f() // OK because now f() is public } Scope of Protection Access modifiers in Scala can be augmented with qualifiers. A modifier of the form private[X] or protected[X] means that access is private or protected “up to” X, where X designates some enclosing package, class or singleton object. Consider the following example − Example package society { package professional { class Executive { private[professional] var workDetails = null private[society] var friends = null private[this] var secrets = null def help(another : Executive) { println(another.workDetails) println(another.secrets) //ERROR } } } } Note − the following points from the above example − Variable workDetails will be accessible to any class within the enclosing package professional. Variable friends will be accessible to any class within the enclosing package society. Variable secrets will be accessible only on the implicit object within instance methods (this). Print Page Previous Next Advertisements ”;

Scala – Pattern Matching

Scala – Pattern Matching ”; Previous Next Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions. Try the following example program, which shows how to match against an integer value. Example object Demo { def main(args: Array[String]) { println(matchTest(3)) } def matchTest(x: Int): String = x match { case 1 => “one” case 2 => “two” case _ => “many” } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output many The block with the case statements defines a function, which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. Try the following example program, which matches a value against patterns of different types. Example object Demo { def main(args: Array[String]) { println(matchTest(“two”)) println(matchTest(“test”)) println(matchTest(1)) } def matchTest(x: Any): Any = x match { case 1 => “one” case “two” => 2 case y: Int => “scala.Int” case _ => “many” } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 2 many one Matching using Case Classes The case classes are special classes that are used in pattern matching with case expressions. Syntactically, these are standard classes with a special modifier: case. Try the following, it is a simple pattern matching example using case class. Example object Demo { def main(args: Array[String]) { val alice = new Person(“Alice”, 25) val bob = new Person(“Bob”, 32) val charlie = new Person(“Charlie”, 32) for (person <- List(alice, bob, charlie)) { person match { case Person(“Alice”, 25) => println(“Hi Alice!”) case Person(“Bob”, 32) => println(“Hi Bob!”) case Person(name, age) => println( “Age: ” &plus; age &plus; ” year, name: ” &plus; name &plus; “?”) } } } case class Person(name: String, age: Int) } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Hi Alice! Hi Bob! Age: 32 year, name: Charlie? Adding the case keyword causes the compiler to add a number of useful features automatically. The keyword suggests an association with case expressions in pattern matching. First, the compiler automatically converts the constructor arguments into immutable fields (vals). The val keyword is optional. If you want mutable fields, use the var keyword. So, our constructor argument lists are now shorter. Second, the compiler automatically implements equals, hashCode, and toString methods to the class, which use the fields specified as constructor arguments. So, we no longer need our own toString() methods. Finally, also, the body of Person class becomes empty because there are no methods that we need to define! Print Page Previous Next Advertisements ”;

Scala – Environment Setup

Scala – Environment Setup ”; Previous Next Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer. Follow the steps given below to install Scala. Step 1: Verify Your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open Command Console and type − >java –version Java version “1.8.0_31” Java (TM) SE Run Time Environment (build 1.8.0_31-b31) Java Hotspot (TM) 64-bit Server VM (build 25.31-b07, mixed mode) Linux Open Command terminal and type − $java –version Java version “1.8.0_31” Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode) We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system. In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it. Step 2: Set Your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk1.7.0_60 2 Linux Export JAVA_HOME=/usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No Platform & Description 1 Windows Append the String “C:Program FilesJavajdk1.7.0_60bin” to the end of the system variable PATH. 2 Linux Export PATH=$PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Step 3: Install Scala You can download Scala from http://www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ‘scala-2.11.5-installer.jar’. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt − Platform Command & Output Description Windows >java –jar scala-2.11.5-installer.jar> This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:Program FilesScala”, you can select a suitable path as per your convenience. Linux Command − $java –jar scala-2.9.0.1-installer.jar Output − Welcome to the installation of Scala 2.9.0.1! The homepage is at − http://Scala-lang.org/ press 1 to continue, 2 to quit, 3 to redisplay 1………………………………………… [ Starting to unpack ] [ Processing package: Software Package Installation (1/1) ] [ Unpacking finished ] [ Console installation done ] During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience. Finally, open a new command prompt and type Scala -version and press Enter. You should see the following − Platform Command Output Windows >scala -version Scala code runner version 2.11.5 — Copyright 2002-2013, LAMP/EPFL Linux $scala -version Scala code runner version 2.9.0.1 – Copyright 2002-2013, LAMP/EPFL Print Page Previous Next Advertisements ”;

Scala – Data Types

Scala – Data Types ”; Previous Next Scala has all the same data types as Java, with the same memory footprint and precision. Following is the table giving details about all the data types available in Scala − Sr.No Data Type & Description 1 Byte 8 bit signed value. Range from -128 to 127 2 Short 16 bit signed value. Range -32768 to 32767 3 Int 32 bit signed value. Range -2147483648 to 2147483647 4 Long 64 bit signed value. -9223372036854775808 to 9223372036854775807 5 Float 32 bit IEEE 754 single-precision float 6 Double 64 bit IEEE 754 double-precision float 7 Char 16 bit unsigned Unicode character. Range from U+0000 to U+FFFF 8 String A sequence of Chars 9 Boolean Either the literal true or the literal false 10 Unit Corresponds to no value 11 Null null or empty reference 12 Nothing The subtype of every other type; includes no values 13 Any The supertype of any type; any object is of type Any 14 AnyRef The supertype of any reference type All the data types listed above are objects. There are no primitive types like in Java. This means that you can call methods on an Int, Long, etc. Scala Basic Literals The rules Scala uses for literals are simple and intuitive. This section explains all basic Scala Literals. Integral Literals Integer literals are usually of type Int, or of type Long when followed by a L or l suffix. Here are some integer literals − 0 035 21 0xFFFFFFFF 0777L Floating Point Literal Floating point literals are of type Float when followed by a floating point type suffix F or f, and are of type Double otherwise. Here are some floating point literals − 0.0 1e30f 3.14159f 1.0e100 .1 Boolean Literals The Boolean literals true and false are members of type Boolean. Symbol Literals A symbol literal ”x is a shorthand for the expression scala.Symbol(“x”). Symbol is a case class, which is defined as follows. package scala final case class Symbol private (name: String) { override def toString: String = “”” &plus; name } Character Literals A character literal is a single character enclosed in quotes. The character is either a printable Unicode character or is described by an escape sequence. Here are some character literals − ”a” ”u0041” ”n” ”t” String Literals A string literal is a sequence of characters in double quotes. The characters are either printable Unicode character or are described by escape sequences. Here are some string literals − “Hello,nWorld!” “This string contains a ” character.” Multi-Line Strings A multi-line string literal is a sequence of characters enclosed in triple quotes “”” … “””. The sequence of characters is arbitrary, except that it may contain three or more consecutive quote characters only at the very end. Characters must not necessarily be printable; newlines or other control characters are also permitted. Here is a multi-line string literal − “””the present string spans three lines.””” Null Values The null value is of type scala.Null and is thus compatible with every reference type. It denotes a reference value which refers to a special “null” object. Escape Sequences The following escape sequences are recognized in character and string literals. Escape Sequences Unicode Description b u0008 backspace BS t u0009 horizontal tab HT n u000c formfeed FF f u000c formfeed FF r u000d carriage return CR “ u0022 double quote “ ” u0027 single quote . \ u005c backslash A character with Unicode between 0 and 255 may also be represented by an octal escape, i.e., a backslash ”” followed by a sequence of up to three octal characters. Following is the example to show few escape sequence characters − Example object Test { def main(args: Array[String]) { println(“HellotWorldnn” ); } } When the above code is compiled and executed, it produces the following result − Output Hello World Print Page Previous Next Advertisements ”;

Rexx – Basic Syntax

Rexx – Basic Syntax ”; Previous Next In order to understand the basic syntax of Rexx, let us first look at a simple Hello World program. Example Live Demo /* Main program */ say “Hello World” One can see how simple the hello world program is. It is a simple script line which is used to execute the Hello World program. The following things need to be noted about the above program − The say command is used to output a value to the console. The /* */ is used for comments in Rexx. The output of the above program will be − Hello World General Form of a Statement In Rexx, let’s see a general form of a program. Take a look at the following example. Live Demo /* Main program */ say add(5,6) exit add: parse arg a,b return a + b The output of the above program will be − 11 Let’s go through what we have understood from the above program − Add is a function defined to add 2 numbers. In the main program, the values of 5 and 6 is used as parameters to the add function. The exit keyword is used to exit from the main program. This is used to differentiate the main program from the add function. The add function is differentiated with the ‘:’ symbol. The parse statement is used to parse the incoming arguments. Finally, the return statement is used to return the sum of the numeric values. Subroutines and Functions In Rexx, the code is normally divided into subroutines and functions. Subroutines and functions are used to differentiate the code into different logical units. The key difference between subroutines and functions is that functions return a value whereas subroutines don’t. Below is a key difference example between a subroutine and a function for an addition implementation − Function Implementation /* Main program */ say add(5,6) exit add: parse arg a,b return a + b Subroutine Implementation /* Main program */ add(5,6) exit add: parse arg a,b say a + b The output of both the programs will be the value 11. Executing Commands Rexx can be used as a control language for a variety of command-based systems. The way that Rexx executes commands in these systems is as follows. When Rexx encounters a program line which is neither an instruction nor an assignment, it treats that line as a string expression which is to be evaluated and then passed to the environment. An example is as follows − Example Live Demo /* Main program */ parse arg command command “file1” command “file2” command “file3″ exit Each of the three similar lines in this program is a string expression which adds the name of a file (contained in the string constants) to the name of a command (given as a parameter). The resulting string is passed to the environment to be executed as a command. When the command has finished, the variable “rc” is set to the exit code of the command. The output of the above program is as follows − sh: file1: command not found 3 *-* command “file1″ >>> ” file1″ +++ “RC(127)” sh: file2: command not found 4 *-* command “file2″ >>> ” file2″ +++ “RC(127)” sh: file3: command not found 5 *-* command “file3″ >>> ” file3″ +++ “RC(127)” Keywords in Rexx The free syntax of REXX implies that some symbols are reserved for the language processor”s use in certain contexts. Within particular instructions, some symbols may be reserved to separate the parts of the instruction. These symbols are referred to as keywords. Examples of REXX keywords are the WHILE in a DO instruction, and the THEN (which acts as a clause terminator in this case) following an IF or WHEN clause. Apart from these cases, only simple symbols that are the first token in a clause and that are not followed by an “=” or “:” are checked to see if they are instruction keywords. You can use the symbols freely elsewhere in clauses without their being taken to be keywords. Comments in Rexx Comments are used to document your code. Single line comments are identified by using the /* */ at any position in the line. An example is as follows − /* Main program */ /* Call the add function */ add(5,6) /* Exit the main program */ exit add: /* Parse the arguments passed to the add function */ parse arg a,b /* Display the added numeric values */ say a + b Comments can also be written in between a code line as shown in the following program − Live Demo /* Main program */ /* Call the add function */ add(5,6) /* Exit the main program */ exit add: parse /* Parse the arguments passed to the add function */ arg a,b /* Display the added numeric values */ say a + b The output of the above program will be − 11 You can also have multiple lines in a comment as shown in the following program − Live Demo /* Main program The below program is used to add numbers Call the add function */ add(5,6) exit add: parse arg a,b say a + b The output of the above program will be − 11 Print Page Previous Next Advertisements ”;

Scala – Loop Statements

Scala – Loop Statements ”; Previous Next This chapter takes you through the loop control structures in Scala programming languages. There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Flow Chart Scala programming language provides the following types of loops to handle looping requirements. Click the following links in the table to check their detail. Sr.No Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 do-while loop Like a while statement, except that it tests the condition at the end of the loop body. 3 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. As such Scala does not support break or continue statement like Java does but starting from Scala version 2.8, there is a way to break the loops. Click the following links to check the detail. Sr.No Control Statement & Description 1 break statement Terminates the loop statement and transfers execution to the statement immediately following the loop. The infinite Loop A loop becomes an infinite loop if a condition never becomes false. If you are using Scala, the while loop is the best way to implement infinite loop. The following program implements infinite loop. Example object Demo { def main(args: Array[String]) { var a = 10; // An infinite loop. while( true ){ println( “Value of a: ” &plus; a ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output If you will execute above code, it will go in infinite loop which you can terminate by pressing Ctrl &plus; C keys. Value of a: 10 Value of a: 10 Value of a: 10 Value of a: 10 ……………. Print Page Previous Next Advertisements ”;

RSpec – Useful Resources

RSpec – Useful Resources ”; Previous Next The following resources contain additional information on RSpec. Please use them to get more in-depth knowledge on this. Python Programming Certification 2024 Most Popular  9 Courses     1 eBooks Tutorialspoint More Detail Artificial Intelligence and Machine Learning Certification 2024 Most Popular  7 Courses     1 eBooks Tutorialspoint More Detail Java Certification 2024 Best Seller  7 Courses     1 eBooks Tutorialspoint More Detail Print Page Previous Next Advertisements ”;

Scala – Home

Scala Tutorial PDF Version Quick Guide Resources Job Search Discussion Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates the features of object-oriented and functional languages. This tutorial explains the basics of Scala in a simple and reader-friendly way. Audience This tutorial has been prepared for beginners to help them understand the basics of Scala in simple and easy steps. After completing this tutorial, you will find yourself at a moderate level of expertise in using Scala from where you can take yourself to next levels. Prerequisites Scala Programming is based on Java, so if you are aware of Java syntax, then it”s pretty easy to learn Scala. Further if you do not have expertise in Java but if you know any other programming language like C, C++ or Python then it will also help in grasping Scala concepts very quickly. Print Page Previous Next Advertisements ”;

Scala – Variables

Scala – Variables ”; Previous Next Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory. Based on the data type of a variable, the compiler allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. Variable Declaration Scala has a different syntax for declaring variables. They can be defined as value, i.e., constant or a variable. Here, myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable. Following is the syntax to define a variable using var keyword − Syntax var myVar : String = “Foo” Here, myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable. Following is the syntax to define a variable using val keyword − Syntax val myVal : String = “Foo” Variable Data Types The type of a variable is specified after the variable name and before equals sign. You can define any type of Scala variable by mentioning its data type as follows − Syntax val or val VariableName : DataType = [Initial Value] If you do not assign any initial value to a variable, then it is valid as follows − Syntax var myVar :Int; val myVal :String; Variable Type Inference When you assign an initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it. This is called variable type inference. Therefore, you could write these variable declarations like this − Syntax var myVar = 10; val myVal = “Hello, Scala!”; Here, by default, myVar will be Int type and myVal will become String type variable. Multiple assignments Scala supports multiple assignments. If a code block or method returns a Tuple (Tuple − Holds collection of Objects of different types), the Tuple can be assigned to a val variable. [Note − We will study Tuples in subsequent chapters.] Syntax val (myVar1: Int, myVar2: String) = Pair(40, “Foo”) And the type inference gets it right − Syntax val (myVar1, myVar2) = Pair(40, “Foo”) Example Program The following is an example program that explains the process of variable declaration in Scala. This program declares four variables — two variables are defined with type declaration and remaining two are without type declaration. Example object Demo { def main(args: Array[String]) { var myVar :Int = 10; val myVal :String = “Hello Scala with datatype declaration.”; var myVar1 = 20; val myVal1 = “Hello Scala new without datatype declaration.”; println(myVar); println(myVal); println(myVar1); println(myVal1); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 10 Hello Scala with datatype declaration. 20 Hello Scala without datatype declaration. Variable Scope Variables in Scala can have three different scopes depending on the place where they are being used. They can exist as fields, as method parameters and as local variables. Below are the details about each type of scope. Fields Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object depending on what access modifiers the field is declared with. Object fields can be both mutable and immutable types and can be defined using either var or val. Method Parameters Method parameters are variables, which are used to pass the value inside a method, when the method is called. Method parameters are only accessible from inside the method but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always immutable which are defined by val keyword. Local Variables Local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both mutable and immutable types and can be defined using either var or val. Print Page Previous Next Advertisements ”;