Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Basic Syntax

Scala Basic Syntax

If you are 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 a Scala statement is optional.

We can think of a Scala program as a collection of objects that communicate by calling each other's methods. Next, let's understand the concepts of classes, objects, methods, and instance variables:


Your First Scala Program

Interactive programming

Interactive programming does not require creating a script file; you can invoke it 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 Mode

We can also execute code by creating a file named HelloWorld.scala, whose code is shown below:

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 that a HelloWorld.class file has been generated in the directory, which can run on the Java Virtual Machine (JVM).

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



$ scala HelloWorld

Hello, world!

Online example »


Basic Syntax

The following points should be noted about Scala's basic syntax:


If several words are needed to form a class name, the first letter of each word should be uppercase.

Example:class MyFirstScalaClass

-

Method Name - 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 uppercase.

Example:def myMethodName()

-

Program File Name - The name of the program file should match the object name exactly (not required in newer versions, but it is recommended to keep this habit).
When saving the file, you should save it with the name of the object it uses (remember that 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: Suppose 'HelloWorld' is the name of the 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 entry point of every Scala program.


Identifiers

Scala can use two forms of identifiers: alphanumeric and symbolic.

Alphanumeric identifiers begin with a letter or an underscore, which can be followed by letters or digits; the symbol '$' is also treated as a letter in Scala. However, identifiers beginning with '$' are reserved for compiler-generated identifiers, so applications should avoid using identifiers starting with '$' to prevent conflicts.

Scala's naming conventions follow a camel-case rule similar to Java's, with a lowercase first character, such as toString. Class names still use an uppercase first character. In addition, you should avoid identifiers ending with an underscore to prevent conflicts. Symbolic identifiers contain one or more symbols, such as +, :, ?, etc., for example:



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

Scala's internal implementation uses escaped identifiers; for example, :-> is represented as $colon$minus$greater. Therefore, if you need to access the :-> method from 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 Scala's internal name for the + method. A literal identifier is a string defined using backticks, such as x yield。

You can use any valid Scala identifier between backticks, and Scala will interpret them as a single 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 the reserved keywords in scala; we cannot use these 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

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



object HelloWorld {

   /* This is a Scala program

    * This is a comment

    * This demonstrates multi-line comments

    */

   def main(args: Array[String]) {

      // Output Hello World

      // This is a single-line comment

      println("Hello, world!") 

   }

}


Blank Lines and Whitespace

A line containing only whitespace or a comment is considered a blank line by Scala and is ignored. Tokens can be separated by whitespace or comments.


Newline

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



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


Scala Packages

Defining a Package

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

The first method, like Java, defines the package name at the top of the file, so all subsequent code is placed in that package. For example:



package com.runoob

class HelloWorld

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



package com.runoob {

  class HelloWorld 

}

With the second method, you can define multiple packages in a single 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,所以可以省去前面的部分

}

An import statement can appear anywhere, not only at the top of a file. The effect of an import extends from its beginning to the end of the enclosing block. This can greatly reduce the possibility of name conflicts.

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

import java.awt.{Color, Font}

 

// Rename member

import java.util.{HashMap => JavaHashMap}

 

// private member

import java.util.{HashMap => _, _} // 引入了util包的所有成员,但是HashMap被隐藏了

Note:By default, Scala always imports java.lang._, scala._, and Predef._, which explains why packages starting with scala are used without the scala. prefix.