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 = “”” + 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 ”;

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 ”;

Scala – Overview

Scala – Overview ”; Previous Next Scala, short for Scalable Language, is a hybrid functional programming language. It was created by Martin Odersky. Scala smoothly integrates the features of object-oriented and functional languages. Scala is compiled to run on the Java Virtual Machine. Many existing companies, who depend on Java for business critical applications, are turning to Scala to boost their development productivity, applications scalability and overall reliability. Here we have presented a few points that makes Scala the first choice of application developers. Scala is object-oriented Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits which will be explained in subsequent chapters. Classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance. Scala is functional Scala is also a functional language in the sense that every function is a value and every value is an object so ultimately every function is an object. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. These concepts will be explained in subsequent chapters. Scala is statically typed Scala, unlike some of the other statically typed languages (C, Pascal, Rust, etc.), does not expect you to provide redundant type information. You don”t have to specify a type in most cases, and you certainly don”t have to repeat it. Scala runs on the JVM Scala is compiled into Java Byte Code which is executed by the Java Virtual Machine (JVM). This means that Scala and Java have a common runtime platform. You can easily move from Java to Scala. The Scala compiler compiles your Scala code into Java Byte Code, which can then be executed by the ”scala” command. The ”scala” command is similar to the java command, in that it executes your compiled Scala code. Scala can Execute Java Code Scala enables you to use all the classes of the Java SDK and also your own custom Java classes, or your favorite Java open source projects. Scala can do Concurrent & Synchronize processing Scala allows you to express general programming patterns in an effective way. It reduces the number of lines and helps the programmer to code in a type-safe way. It allows you to write codes in an immutable manner, which makes it easy to apply concurrency and parallelism (Synchronize). Scala vs Java Scala has a set of features that completely differ from Java. Some of these are − All types are objects Type inference Nested Functions Functions are objects Domain specific language (DSL) support Traits Closures Concurrency support inspired by Erlang Scala Web Frameworks Scala is being used everywhere and importantly in enterprise web applications. You can check a few of the most popular Scala web frameworks − The Lift Framework The Play framework The Bowler framework Print Page Previous Next Advertisements ”;

Scala – Basic Syntax

Scala – Basic Syntax ”; Previous Next If you have a good understanding on Java, then it will be very easy for you to learn Scala. The biggest syntactic difference between Scala and Java is that the ”;” line end character is optional. When we consider a Scala program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods and instance variables mean. Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states – color, name, breed as well as behaviors – wagging, barking, and eating. Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class. Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Fields − Each object has its unique set of instance variables, which are called fields. An object”s state is created by the values assigned to these fields. Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function. Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods. First Scala Program We can execute a Scala program in two modes: one is interactive mode and another is script mode. Interactive Mode Open the command prompt and use the following command to open Scala. >scala If Scala is installed in your system, the following output will be displayed − Welcome to Scala version 2.9.0.1 Type in expressions to have them evaluated. Type :help for more information. Type the following text to the right of the Scala prompt and press the Enter key − scala> println(“Hello, Scala!”); It will produce the following result − Hello, Scala! Script Mode Use the following instructions to write a Scala program in script mode. Open notepad and add the following code into it. Example Live Demo object HelloWorld { /* This is my first java program. * This will print ”Hello World” as the output */ def main(args: Array[String]) { println(“Hello, world!”) // prints Hello World } } Save the file as − HelloWorld.scala. Open the command prompt window and go to the directory where the program file is saved. The ‘scalac’ command is used to compile the Scala program and it will generate a few class files in the current directory. One of them will be called HelloWorld.class. This is a bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command. Use the following command to compile and execute your Scala program. > scalac HelloWorld.scala > scala HelloWorld Output Hello, World! Basic Syntax The following are the basic syntaxes and coding conventions in Scala programming. Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala. Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word”s first letter should be in Upper Case. Example − class MyFirstScalaClass. Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word”s first letter should be in Upper Case. Example − def myMethodName() Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile). Example − Assume ”HelloWorld” is the object name. Then the file should be saved as ”HelloWorld.scala”. def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program. Scala Identifiers All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. Scala supports four types of identifiers. Alphanumeric Identifiers An alphanumeric identifier starts with a letter or an underscore, which can be followed by further letters, digits, or underscores. The ”$” character is a reserved keyword in Scala and should not be used in identifiers. Following are legal alphanumeric identifiers − age, salary, _value, __1_value Following are illegal identifiers − $salary, 123abc, -salary Operator Identifiers An operator identifier consists of one or more operator characters. Operator characters are printable ASCII characters such as +, :, ?, ~ or #. Following are legal operator identifiers − &plus; &plus;&plus; ::: <?> :> The Scala compiler will internally “mangle” operator identifiers to turn them into legal Java identifiers with embedded $ characters. For instance, the identifier :-> would be represented internally as $colon$minus$greater. Mixed Identifiers A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore and an operator identifier. Following are legal mixed identifiers − unary_&plus;, myvar_= Here, unary_&plus; used as a method name defines a unary &plus; operator and myvar_= used as method name defines an assignment operator (operator overloading). Literal Identifiers A literal identifier is an arbitrary string enclosed in back ticks (` . . . `). Following are legal literal identifiers − `x` `<clinit>` `yield` Scala Keywords The following list shows the reserved words in Scala. These reserved words may not be used as constant or variable or any other identifier names. abstract case catch class def do else extends false final finally for forSome if implicit import lazy match new Null object override package private protected return sealed super this throw trait Try true type val