Scala Basic Syntax

If you were a Java programmer and understand the basics of the Java language, 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 think of Scala programs as collections of objects that implement message passing by calling each other's methods. Next, let's understand the concepts of classes, objects, methods, and instance variables:

  • Object -Objects have properties and behaviors. For example: a dog's state properties are: color, name; behaviors are: bark, run, eat, etc. An object is an instance of a class.

  • Class -A class is an abstraction of objects, and an object is a concrete instance of a class.

  • Method -Methods describe basic behaviors. A class can contain multiple methods.

  • Field -Every object has its own unique set of instance variables, namely fields. The properties of an object are created by assigning values to fields.


First Scala Program

Interactive Programming

Interactive programming does not require creating script files; 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 HelloWorld.scala file. The HelloWorld.scala code 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[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 the HelloWorld.class file generated in the directory. This file can run on the Java Virtual Machine (JVM).

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

$ scala HelloWorld
Hello, world!

Online Example »


Basic Syntax

The following points should be noted about Scala basic syntax:

  • Case Sensitivity- Scala is case-sensitive, which means that the identifiers Hello and hello have different meanings in Scala.

  • Class Names- For all class names, the first letter should be capitalized.
    If several words are used 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 word should be capitalized.

    Example:def myMethodName()

  • Program File Names- The file name of the program should exactly match the object name (newer versions no longer require this, but it is recommended to keep this habit).
    When saving the file, you should save it with the object name it uses (remember Scala is case-sensitive) and append ".scala" as the file extension. (If the file name and the object name do not match, the program will not compile).

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

  • def main(args: Array[String]) - Scala programs start processing from the main() method, which is the mandatory program 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, and can be followed by letters or digits. The symbol "$" is also considered a letter in Scala. However, identifiers starting with "$" are reserved for identifiers generated by the Scala compiler. Applications should avoid using identifiers starting with "$" to prevent conflicts.

Scala's naming rules adopt camel case naming rules similar to Java, with the first character lowercase, such as toString. The first character of class names is still uppercase. In addition, you should also avoid using identifiers ending with an underscore to avoid conflicts. Symbolic identifiers contain one or more symbols, such as +, :, ?, etc., for example:

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

Scala uses escaped identifiers in its internal implementation. For example, :-> is represented by $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. For example, unary_+ is the name Scala uses for the internal implementation of the + method. Literal identifiers are strings defined using backticks, such as `x` and `yield`.

You can use any valid Scala identifier between backticks, and Scala interprets it as a Scala identifier. A typical use 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 Scala reserved keywords. 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, like Java, supports single-line and multi-line comments. Multi-line comments can be nested, but must be properly nested; a comment start symbol corresponds to an end symbol. Comments are ignored during Scala compilation. Examples are as follows:

object HelloWorld {
   /* 这是一个 Scala 程序
    * 这是一行注释
    * 这里演示了多行注释
    */
   def main(args: Array[String]) {
      // 输出 Hello World
      // 这是一个单行注释
      println("Hello, world!") 
   }
}

Blank Lines and Spaces

If a line contains only spaces or consists of a comment, Scala treats it as a blank line and ignores it. Tokens can be separated by spaces or comments.


Line Breaks

Scala is a line-oriented language. Statements can be terminated with a semicolon (;) or a newline. In Scala programs, the semicolon at the end of a statement is usually optional. You can type one if you like, but it can be omitted if there is only one statement on a line. On the other hand, if there are multiple statements on one line, semicolons are required. For example

val s = "Example"; println(s)

Scala Packages

Defining Packages

Scala uses the package keyword to define packages. In Scala, there are two ways to define code in a package:

The first method is the same as Java: define the package name at the top of the file. With this method, all subsequent code is placed in that package. For example:

package com.example
class HelloWorld

The second method is somewhat similar to C#, for example:

package com.example {
  class HelloWorld 
}

With the second method, you can define multiple packages in one file.

Imports

Scala uses the import keyword to import packages.

import java.awt.Color  // 引入Color
 
import java.awt._  // 引入包内所有成员
 
def handler(evt: event.ActionEvent) { // java.awt.event.ActionEvent
  ...  // 因为引入了java.awt,所以可以省去前面的部分
}

Import statements can appear anywhere, not just at the top of a file. The effect of an import extends from the point where it starts to the end of the enclosing block. This can greatly reduce the possibility of name conflicts.

If you want to import several members of a package, you can use a selector:

import java.awt.{Color, Font}
 
// 重命名成员
import java.util.{HashMap => JavaHashMap}
 
// 隐藏成员
import java.util.{HashMap => _, _} // 引入了util包的所有成员,但是HashMap被隐藏了

Note:By default, Scala always imports java.lang._, scala._, and Predef._. This also explains why packages starting with scala can omit the scala. prefix when used.

Other Extensions