Scala basic syntax


If you are a Java programmer before and know 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 a Scala statement is optional.

We can think of a Scala program as a collection 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:

  • Objects - Objects have properties and behaviors. For example: a dog's attributes 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 concrete instance of a class.

  • Method - Method describes the basic behavior. A class can contain multiple methods.

  • Fields - Each object has its unique set of instance variables, which are fields. Object properties 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. The HelloWorld.scala code is as follows:

object HelloWorld {
   /* 这是我的第一个 Scala 程序
    * 以下程序将输出'Hello World!' 
    */
   def main(args: Array[String]) {
      println("Hello, world!") // 输出 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 example»

Basic syntax

Scala basic syntax needs attention The following points:

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

  • Class Name - Capitalize the first letter of all class names.

    If you need to use several words to form a class name, capitalize the first letter of each word.

    Example: class MyFirstScalaClass

  • Method Name - The first letter of all method names is lowercase.

    If several words are used to form the name of a method, the first letter of each word should be capitalized.

    Example: def myMethodName()

  • Program File Name - The name of the program file should exactly match the object name .

    When saving a 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: Assume "HelloWorld" is the name of the object. Then the file should be saved as 'HelloWorld.scala"

  • def main(args: Array[String]) - The 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, alphanumeric and symbols.

Character numbers start with letters or underscores, and can be followed by letters or numbers. The symbol "$" is also regarded as a letter in Scala. However, identifiers starting with "$" are reserved for use in identifiers generated by the Scala compiler, and applications should avoid using identifiers starting with "$" to avoid conflicts.

Scala’s naming rules adopt camel naming rules similar to Java, with the first character lowercase, such as toString. The first character of the class name is still capitalized. Also avoid using identifiers ending with an underscore to avoid conflicts. Symbol identifiers contain one or more symbols, such as +, :, ?, etc., for example:

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

Scala will use escaped identifiers during internal implementation, such as: -> Use $colon$minus$ greater to represent this symbol. So 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 name of Scala’s internal implementation of the + method. Literal identifiers are strings defined using ", such as `x` `yield`.

You can use any valid Scala identifier between ", and Scala will interpret them as a Scala identifier, A typical use is the yield method of Thread. You cannot use Thread.yield() in Scala 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:

##defdo elseextendsfalsefinalfinallyforforSomeifimplicitimportlazymatchnewnullobjectoverridepackageprivateprotectedreturnsealedsuperthisthrowtraittrytruetypevalvarwhilewithyield-:==><-<:<%>:#@##

Scala Comments

Scala supports single-line and multiple-line comments similar to Java. Multi-line comments can be nested, but they must be nested correctly. One comment start symbol corresponds to one end symbol. Comments will be ignored during Scala compilation. Examples are as follows:

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

Empty lines and spaces

If there are only spaces or comments in a line, Scala will consider it to be an empty line and will ignore it. Tags can be separated by spaces or comments.


Newline character

Scala is a line-oriented language, and 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 enter one if you wish, but if there is only You don’t have to write a single statement. On the other hand, if you write multiple statements in one line then semicolons are required. For example

val s = "php中文网"; println(s)

Scala package

Define package

Scala uses the package keyword to define a package. There are two ways to define code into a package in Scala:

The first method is the same as Java, defining the package name in the header of the file. In this method, all subsequent code will be placed in the package. For example:

package com.php
class HelloWorld

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

package com.php {
  class HelloWorld 
}

The second method allows you to define multiple packages in one file.

Reference

Scala uses the import keyword to reference 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 the file. The effect of import extends from the beginning to the end of the statement block. This greatly reduces the possibility of name conflicts.

If you want to introduce several members in the package, you can use the selector (selector):

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

Note: By default, Scala will always Introducing java.lang._, scala._ and Predef._, this can also explain why packages starting with scala omit scala. when using them.

abstractcasecatchclass