Page Contents
Scala Language Basic Syntax
The easiest way to start working with Scala is REPL : Read -Evaluate – Print – Loop. We can execute a Scala program in two modes: Interactive mode and another is script mode.
Interactive Mode – Scala Program using REPL
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, Proedu.co!");
It will produce the following result −
Hello, Proedu.co!
Script Mode
Open a text editor and add the following code in it.
Example
object Demo extends App{ println("Hello, Proedu.co!") }
Save the file as Demo.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. It will generate a class file named Demo.class. Now run this class using ‘scala‘ command.
scalac Demo.scala scala Demo
Output
Hello, Proedu.co!
Basic Syntax
The following are the basic syntax’s and coding conventions in Scala programming.
- Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning.
- Class Names − The class names should be in Camel case. If several words are used to form a name of the class, each word’s first letter should be in Upper Case. For example MyDemoProgram.scala
- 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 word’s first letter should be in Upper Case. For example def doSomething()
- Scala 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.
- def main(args: Array[String]) − Scala program processing starts from the main() method. A class can also extend App trait instead of providing the main method.
Scala Identifiers
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.
name, _count , __1_value
Below identifiers are not allowed
$name, 123count, -value
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 −
+ ++ ::: <?> :>
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.
unary_+, myvar_=
Here, unary_+ used as a method name defines a unary + 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 | Var |
while | with | yield | |
– | : | = | => |
<- | <: | <% | >: |
# | @ |
Comments in Scala
Scala supports single-line and multi-line comments very similar to Java. Multi-line comments may be nested, but are required to be properly nested. All characters available inside any comment are ignored by Scala compiler.
object CommentsDemo{ /* This is an example of multi-line comment. * The below example prints Hello Proedu. */ def main(args: Array[String]) { // This is an example of single line comment. println("Hello, Proedu!") } }
Blank Lines and Whitespace
A line containing only whitespace, possibly with a comment, is known as a blank line, and Scala totally ignores it. Tokens may be separated by whitespace characters and/or comments.
Newline Characters
Scala is a line-oriented language where statements may be terminated by semicolons (;) or newlines. A semicolon at the end of a statement is not mandatory. Semicolon is only required if you write multiple expressions in a single line.
val message = "Hello Proedu.co"; println(message)
Scala Packages
Creating a package
Scala uses packages to create namespaces which allow you to modularize programs.Packages are created by declaring one or more package names at the top of a Scala file.
package billing class Cart
The package name should be all lower case and if the code is being developed within an organization which has a website, it should be the following format convention: <top-level-domain>.<domain-name>.<project-name>
. For example, if Proedu.co has a project called TutorialHub
, the package name would look like this:
package co.proedu.tutorialhub.users class User class UserPreferences
Importing a package
import
clauses are for accessing members (classes, traits, functions, etc.) in other packages. An import
clause is not required for accessing members of the same package. Import clauses are selective:
import users._ // import everything from the users package import users.User // import the class User import users.{User, UserPreferences} // Only imports selected members import users.{UserPreferences => UPrefs} // import and rename for convenience
NOTE:
- One way in which Scala is different from Java is that imports can be used anywhere:
- In the event there is a naming conflict and you need to import something from the root of the project, prefix the package name with root. Example –
package accounts import root.users._
Apply Dynamic
A marker trait that enables dynamic invocations. Instances x
of this trait allow method invocations x.meth(args)
for arbitrary method names meth
and argument lists args
as well as field accesses x.field
for arbitrary field names field
.
If a call is not natively supported by x (i.e. if type checking fails), it is rewritten according to the following rules −
foo.method("blah") ~~> foo.applyDynamic("method")("blah") foo.method(x = "blah") ~~> foo.applyDynamicNamed("method")(("x", "blah")) foo.method(x = 1, 2) ~~> foo.applyDynamicNamed("method")(("x", 1), ("", 2)) foo.field ~~> foo.selectDynamic("field") foo.varia = 10 ~~> foo.updateDynamic("varia")(10) foo.arr(10) = 13 ~~> foo.selectDynamic("arr").update(10, 13) foo.arr(10) ~~> foo.applyDynamic("arr")(10)