WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Scala - Basic Syntax


If you were a Java programmer and understood 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 the Scala statement 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:

  • Objects - Objects have properties and behaviors. For example, the characteristics of a dog are: color, name, behavior: call, run, eat, etc. An object is an instance of a class.

  • The
  • class- class is an abstraction of the object, and the object is a concrete instance of the class.

  • Methods - The basic behavior of a method description, a class can contain multiple methods.

  • Fields - Each object has its own unique set of instance variables, the fields. The properties of an object are created by assigning a value to the field.


First Scala program

Interactive programming

Interactive programming does not require the creation of a script file, which 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 looks like this:

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 compile it using the scalac command:

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

After compiling 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!


Basic syntax

The basic syntax of Scala requires attention to the following:

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

  • Class name - The first letter of all Class names is capitalized.
    If you need to use a few words to form the name of a class, the first letter of each word should be capitalized.

    example:class MyFirstScalaClass

  • Method name -The first letter of all Method names is in 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 match the object name exactly (the new version is not needed, but it is recommended to keep this habit).
    When saving a file, you should save the object name it uses (remember that Scala is case sensitive) and append".scAla" is the file extension. (If the file name and object name do not match, the program will not compile).

    Example: Suppose "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 with the main() method, which is the mandatory program entry for each Scala program.


Identifier

Scala can use two forms of identifiers, character numbers and symbols.

Character numbers begin with a letter or an underscore, followed by a letter or number, and the symbol "$" is also treated as a letter in Scala. However, identifiers starting with "$" are used by the identifiers generated by the reserved Scala compiler, and applications should avoid using identifiers starting with "$" to avoid conflicts.

Scala's naming convention uses a similar camel naming convention like Java, with the first character lowercase, such as toString. The first character of the class name is still in uppercase. You should also avoid using identifiers that end with an underscore to avoid conflicts. The symbol identifier contains one or more symbols, such as +, :, ?, etc., for example:

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

The escaped identifier is used in Scala's internal implementation, such as:-> Use $colon$minus$greater to represent this symbol. So if you need to access it in Java code:->Method you need to use Scala 'S internal name$colon$minus$greater。

A mixed identifier consists of a character number identifier followed by one or more symbols, such as unary_+ as the name of the internal implementation of the Scala pair + method. The literal identifier is "using a defined string, such as `x` `yield`.

You can use any valid Scala identifier between them, Scala interprets them as a Scala identifier A typical yield method that uses Thread. You can't use Thread.yield() in Scala because yield is a keyword in Scala. You must use Thread.`yield`() to use this method.


Scala keyword

The following table lists the scala reserved keywords, and we can't 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 annotation

Scala is similar to Java and supports single-line and multi-line comments. Multi-line comments can be nested, but must be nested correctly, with a comment start symbol corresponding to an end symbol. Comments are ignored in Scala compilation, examples are as follows:

object HelloWorld {
   /* This is a Scala program
    * This is a line of comments
    * Demonstrated multi-line comments here
    */
   def main(args: Array[String]) {
      // Output Hello World
      // This is a one-line comment
      Println("Hello, world!")
   }
}

empty lines and spaces

There is only a space or a comment in a line, Scala will consider it a blank line and will ignore it. Tags can be split by spaces or comments.


Line breaks

Scala is a line-oriented language, and statements can end with a semicolon (;) or a newline character. In Scala programs, the semicolon at the end of the statement is usually optional. If you want, you can enter one, but if only one line There is a statement or not. On the other hand, a semicolon is needed if multiple statements are written in a single line. For example

val s = "welookups Tutorial"; println(s)

Scala package

Definition package

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

The first method, like Java, defines the package name in the header of the file. This method puts all subsequent code in the package. such as:

package com.welookups
class HelloWorld

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

package com.welookups {
  class HelloWorld 
}

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

Reference

Scala uses the import keyword to reference packages.

import java.awt.Color  // IntroduceColor
 
import java.awt._  // Introduce all members of the package
 
def handler(evt: event.ActionEvent) { // java.awt.event.ActionEvent
  ...  // Because java.awt is introduced, the previous 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 collisions.

If you want to introduce several members of the package, you can use the selector:

import java.awt.{Color, Font}
 
// Rename member
import java.util.{HashMap => JavaHashMap}
 
// Hidden member
import java.util.{HashMap => _, _} // Introduce utilAll members of the package, but the HashMap is hidden

Note: By default, Scala always introduces java.lang._ , scala._ , and Predef._ , which can also explain why packages starting with scala are in use. It is to save scala.