English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Basic Syntax

If you are a Java programmer before and understand the basic knowledge of the Java language, then you can quickly learn the basic syntax of Scala.

The biggest difference between Scala and Java is that the semicolon ; at the end of Scala statements is optional.

We can consider Scala programs as collections of objects, which implement message passing by calling each other's methods. Next, let's understand the concepts of class, object, method, and example variables:

  • Object - Objects have properties and behaviors. For example: a dog's status properties include: color, name, and 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 specific instance of a class.

  • Methods - Methods describe the basic behavior, and a class can contain multiple methods.

  • Fields - Each object has a unique set of instance variables, that is, fields. The properties of an object are created by assigning values to fields.

The first Scala program

Interactive programming

Interactive programming does not require the creation of a script file and can be called 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 the code by creating a HelloWorld.scala file, and the HelloWorld.scala code is as follows:

object HelloWorld {
   /* This is my first Scala program
    * The following program will output 'Hello World!' 
    */
   def main(args: Array[String]) {
      println("Hello, world!") // Output Hello World
   }
}

Next, we use the scalac command to compile it:

$ scalac HelloWorld.scala 
$ ls
HelloWorld$.class    HelloWorld.scala
HelloWorld.class

After compilation, we can see that the HelloWorld.class file is generated in the directory, which can be run on the Java Virtual Machine (JVM).

After compilation, we can use the following command to execute the program:

$ scala HelloWorld
Hello, world!

Online examples »

Basic syntax

The following points should be noted in the basic syntax of Scala:

  • Case sensitivity -  Scala is case-sensitive, which means Hello and hello have different meanings in Scala.

  • Class name - The first letter of all class names should be capitalized.
    If a class name is composed of several words, the first letter of each word should be capitalized.

    Example:class MyFirstScalaClass

  • Method name - The first letter of all method names should be lowercase.
    If several words are used to form the name of the method, the first letter of each word should be capitalized.

    Example:def myMethodName()

  • Program file name - The name of the program file should match the object name completely (this is no longer required in the new version, but it is recommended to maintain this habit).
    When saving the file, you should save it using the object name (remember that Scala is case-sensitive), and append ".scala" as the file extension. (If the filename does not match the object name, the program will not compile).

    Example: Assuming "HelloWorld" is the name of an object. Then the file should be saved as 'HelloWorld.scala'

  • def main(args: Array[String]) - A Scala program starts processing from the main() method, which is the mandatory program entry part of every Scala program.

Identifier

Scala can use two forms of identifiers, numeric and symbolic.

Numeric identifiers start with a letter or underscore, followed by letters or numbers, and 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 avoid conflicts.

Scala's naming conventions follow a camel case naming convention similar to Java, with the first character in lowercase, such as toString. The first character of class names should still be uppercase. Additionally, it is also recommended to avoid using identifiers ending with underscores to avoid conflicts. Symbolic identifiers contain one or more symbols, such as+, :, ? and so on, such as:

+ ++ ::: < ?> :->

Scala will use escaped identifiers internally, such as:-> Use $colon$minus$greater to represent this symbol. Therefore, if you need to access in Java code:-> Method, you need to use Scala's internal name $colon$minus$greater.

Mixed identifiers consist of a numeric identifier followed by one or more symbols, such as unary_+ For Scala's+The name used in the internal implementation of the method. Literal identifiers are strings defined using "", such as `x` `yield`.

You can use any valid Scala identifier within "", and Scala will interpret them as an identifier. A typical use is the Thread's yield method; in Scala, you cannot use Thread.yield() because yield is a keyword in Scala, and you must use Thread.`yield`() to use this method.

Scala keywords

The following table lists the reserved keywords in Scala, and we cannot use the following keywords as variables:

abstractcasecatchclass
defdoelseextends
falsefinalfinallyfor
forSomeifimplicitimport
lazymatchnewnull
objectoverridepackageprivate
protectedreturnsealedsuper
thisthrowtraittry
truetypevalvar
whilewithyield 
-:==>
<-<:<%>:
#@

Scala comments

Scala, like Java, supports single-line and multi-line comments. Multi-line comments can be nested, but they must be correctly nested, with one start symbol corresponding to one end symbol. Comments are ignored during Scala compilation, as shown below:

object HelloWorld {
   /* This is a Scala program
    * This is a line comment
    * Here is an example of multi-line comments
    */
   def main(args: Array[String]) {
      // Output Hello World
      // This is a single-line comment
      println("Hello, world!") 
   }
}

Blank lines and spaces

If a line contains only spaces or comments, Scala will consider it as a blank line and ignore it. Marks can be separated by spaces or comments.

Newline character

Scala is a language oriented to lines, where statements can be terminated with a semicolon (;) or a newline character. In Scala programs, the semicolon at the end of a statement is typically optional. You can enter one if you wish, but if only There is also a statement that can be omitted. On the other hand, if multiple statements are written on one line, a semicolon is required. For example

val s = "Basic Tutorial Website"; println(s)

Scala package

Define a package

Scala uses the package keyword to define a package, and there are two ways to define code within a package in Scala:

The first method is similar to Java, where the package name is defined at the beginning of the file, and all subsequent code is placed within this package. For example:

package com.w3codebox
class HelloWorld

The second method is somewhat similar to C#, such as:

package com.w3codebox {
  class HelloWorld 
}

The second method is to define multiple packages in a single file.

Reference

Scala uses the import keyword to reference packages.

import java.awt.Color  // Import Color
 
import java.awt._  // Import all members of the package
 
def handler(evt: event.ActionEvent) { // java.awt.event.ActionEvent
  ...  // Because java.awt was imported, the preceding part can be omitted
}

Import statements 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 greatly reduce the possibility of name conflicts.

If you want to import only some members of a package, you can use a selector (selector):

import java.awt.{Color, Font}
 
// Renaming Members
import java.util.{HashMap => JavaHashMap}
 
// Hidden Members
import java.util.{HashMap => _, _} // All members of the util package are imported, but HashMap is hidden.

Note:By default, Scala always imports java.lang._, scala._, and Predef._, which also explains why packages starting with scala. are often omitted when used.