Scala Basic Syntax
If you were previously a Java programmer and understand the basics of the Java language, you will be able to learn Scala's basic syntax very quickly.
The biggest difference between Scala and Java is that the semicolon (;) at the end of a Scala statement is optional.
We can think of a Scala program as a collection of objects that communicate with each other by calling each other's methods. Next, let's understand the concepts of classes, objects, methods, and instance variables:
* **Object -** Objects have attributes and behaviors. For example: a dog's attributes include: color, name, and its behaviors include: barking, running, eating, etc. An object is an instance of a class.
* **Class -** A class is an abstraction of an object, and an object is a concrete instance of a class.
* **Method -** A method describes basic behaviors, and a class can contain multiple methods.
* **Field -** Each object has its unique set of instance variables, i.e., fields. An object's attributes are created by assigning values to fields.
* * *
## First Scala Program
### Interactive Programming
Interactive programming does not require creating a script file; it can be invoked with the following command:
$ scala Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_31).Type in expressions to have them evaluated.Type :help for more information. scala> 1 + 1 res0: Int = 2 scala> println("Hello World!")Hello World! scala>
* * *
## Script Form
We can also execute code by creating a file named HelloWorld.scala. The code for HelloWorld.scala is as follows:
## HelloWorld.scala File Code:
object HelloWorld {
/* This is my first Scala program
* The following program will output 'Hello World!'
*/
def main(args: Array)={
println("Hello, world!")// Output Hello World
}
}
Next, we use the scalac command to compile it:
$ scalac HelloWorld.scala $ ls HelloWorld$.classHelloWorld.scala HelloWorld.class
After compiling, we can see that a HelloWorld.class file is generated in the directory, which can be run on the Java Virtual Machine (JVM).
After compiling, we can use the following command to execute the program:
$ scala HelloWorldHello, world!
[Online Example Β»](#)
* * *
## Basic Syntax
There are a few points to note regarding Scala basic syntax:
* **Case Sensitivity** - Scala is case-sensitive, which means that the identifiers Hello and hello have different meanings in Scala.
* **Class Names** - The first letter of all class names should be capitalized.
If several words are needed to form a class name, the first letter of each word should be capitalized.
Example: _class MyFirstScalaClass_
* **Method Names** - The first letter of all method names should be lowercase.
If several words are used to form a method name, the first letter of each subsequent word should be capitalized.
Example: _def myMethodName()_
* **Program File Name** - The name of the program file should exactly match the object name (this is no longer required in newer versions, but it is recommended to keep this habit).
When saving the file, you should save it using the object name (remember Scala is case-sensitive) and append ".scala" as the file extension. (If the file name and object name do not match, the program will not compile).
Example: Assuming "HelloWorld" is the object name. Then the file should be saved as 'HelloWorld.scala"
* **def main(args: Array)** - Scala programs start processing from the main() method, which is a mandatory entry point for every Scala program.
* * *
## Identifiers
Scala can use two forms of identifiers: alphanumeric and symbolic.
Alphanumeric identifiers start with a letter or an underscore, followed by letters or numbers. The symbol "$" is also considered a letter in Scala. However, identifiers starting with "$" are reserved for identifiers generated by the Scala compiler, and applications should avoid using identifiers starting with "$" to prevent conflicts.
Scala's naming convention uses a camelCase rule similar to Java, with the first character in lowercase, such as toString. The first character of a class name is still capitalized. Additionally, you should avoid using identifiers ending with an underscore to prevent conflicts. Symbolic identifiers contain one or more symbols, such as +, :, ?, etc., for example:
+ ++ ::: :->
Scala internally uses escaped identifiers; for example, :-> is represented using $colon$minus$greater. Therefore, if you need to access the :-> method in Java code, you need to use Scala's internal name $colon$minus$greater.
Mixed identifiers consist of an alphanumeric identifier followed by one or more symbols, such as unary_+, which is the internal implementation name for the + method in Scala. Literal identifiers are strings defined using backticks, such as `x` `yield`.
You can use any valid Scala identifier between backticks, and Scala will interpret it as a Scala identifier. A typical use case is the yield method of Thread. In Scala, you cannot use Thread.yield() because yield is a keyword in Scala; you must use Thread.`yield`() to use this method.
* * *
## Scala Keywords
The following table lists the reserved keywords in Scala; we cannot use the following keywords as variables:
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
-:==>
<-<::
#@
* * *
## Scala Comments
Scala, similar to Java, supports single-line and multi-line comments. Multi-line comments can be nested, but they must be properly nested, with one closing symbol for every opening symbol. Comments are ignored during Scala compilation, as shown in the following example:
object HelloWorld { /* This is a Scala program * This is a comment * Here demonstrates a multi-line comment */ def main(args: Array) { // Output Hello World // This is a single-line comment println("Hello, world!") }}
* * *
## Blank Lines and Spaces
A line containing only spaces or comments is considered a blank line by Scala and will be ignored. Tokens can be separated by spaces or comments.
* * *
## Newline Characters
Scala is a line-oriented language; statements can be terminated with a semicolon (;) or a newline character. In Scala programs, the semicolon at the end of a statement is usually optional. You can input one if you wish, but if there is only one statement on a line, it can be omitted. On the other hand, if multiple statements are written on a single line, semicolons are required. For example
val s = "Tutorial"; println(s)
* * *
## Scala Packages
### Defining a Package
Scala uses the package keyword to define a package. There are two ways to define code within a certain package in Scala:
The first method is the same as Java, defining the package name at the head of the file; this method means all subsequent code is placed in that package. For example:
package com.tutorial class HelloWorld
The second method is somewhat similar to C#, as follows:
package com.tutorial { class HelloWorld }
The second method allows you to define multiple packages in a single file.
### Imports
Scala uses the import keyword to import packages.
import java.awt.Color // Import Color import java.awt._ // Import all members in the package def handler(evt: event.ActionEvent) { // java.awt.event.ActionEvent ... // Because java.awt was imported, the preceding part can be omitted}
The import statement can appear anywhere, not just at the top of the file. The effect of import extends from the beginning to the end of the statement block. This can significantly reduce the possibility of name conflicts.
If you want to import a few members from a package, you can use a selector:
import java.awt.{Color, Font} // Rename memberimport java.util.{HashMap => JavaHashMap} // Hide memberimport java.util.{HashMap => _, _} // Imported all members of the util package, but HashMap is hidden
> **Note:** By default, Scala always imports java.lang._ , scala._ , and Predef._. This also explains why packages starting with scala. can have the scala. prefix omitted when used.
YouTip