Scala basic syntax
If you used to be a Java programmer 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 the Scala statement is optional.
We can think of Scala programs as collections of objects that implement message delivery by calling each other’s methods. Next, let’s understand theconcepts of classes, objects, methods, and instance variables:
Objects-objects have properties and behaviors. For example, the shape attributes of a dog are: color, name, behavior: 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-the basic behavior described by a method, and a class can contain multiple methods.
Fields-each object has its unique collection of instance variables, that is,fields. The properties of the object are created by assigning values to thefield.
The first Scala program
Interactive programming
Interactive programming does not need to create a script file, and can be called by 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 create a HelloWorld.scala
to execute the code HelloWorld.scala
the 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 compiling, we can see the generation in the directory. HelloWorld.class
file, which can be run on Java Virtual Machine (JVM).
After compilation, we can use the following command to execute the program:
$ scala HelloWorld
Hello, world!
Basic grammar
The basic syntax of Scala should pay attention to the following points:
Case sensitive-Scala is case sensitive, which means that identifying Hello and hello have different meanings in Scala.
- Class name-capitalize the first letter of all class names.If you need to use several 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 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 (the new version is not needed, but it is recommended to keep this habit).When you save a file, you should save the name of the object it uses (remember that Scala is case sensitive) and append “.scala” to 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])
-Scala program frommain()
method, which is the mandatory entry part of each Scala program.
Identifier
Scala can use two forms of markers, characters, numbers and symbols.
Character numbers begin with letters or underscores, followed by letters or numbers, and the symbol “$” is also regarded as a letter in Scala. However, identifiers starting with “$” are used as reserved markers generated by the Scala compiler, and applications should avoid using identifiers that start with “$” to avoid conflicts.
The naming convention of Scala is similar to that of Java, with the first character in lowercase, such as toString
. The first character of the class name is still capitalized. You should also avoid using flags that end with an underscore to avoid conflicts. Symbol markers contain one or more symbols, such as +,:,? Wait, for example:
+ ++ ::: < ?> :->
Escaped markers are used when implemented internally in Scala, such as :->
use $colon$minus$greater
to represent this symbol. So if you need to access the:-> method in your Java code, you need to use the internalname of Scala $colon$minus$greater
.
A mixed character consists of a character numeric marker followed by one or more symbols, such as unary_+
is the name of the internal implementation of the + method by Scala. The literal marker is a string defined with “, such asxyield.
You can use any valid Scala marker between `"
, which Scala interprets as a Scala marker, a typical use of Thread
of yield
method, you cannot use it in Scala Thread.yield()
It’s because yield
for keywords in Scala, you must use the Thread.`yield`()
to use this method.
Scala keyword
The following table lists scala
keep the keyword, we cannot use the following keyword as variable:
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 comment
Scala is similar to Java to support single-line and multi-line comments. Multiline comments can be nested, but they must be nested correctly, with a comment start symbol corresponding to an end symbol. Comments are ignored inScala compilation. Examples are as follows:
Object HelloWorld{
/*This is a Scala program
*This is a line of comments
*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 spaces
There are only spaces or comments on a line, and Scala considers it to be a blank line and ignores it. Tags can be divided by spaces or comments.
Newline character
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 astatement is usually optional. You can enter one if you like, but you can not write if there is only one statement in a line. On the other hand, a semicolon is required if more than one statement is written on a line. For example
val s = "Novice Tutorial"; println(s)
Scala package
Define the package
Scala usage package
keyword to define a package, there are two ways to define code into a package in Scala:
The first method, like Java, defines the package name in the header of the file, and all subsequent code is placed in the package. For example:
package com.runoob
class HelloWorld
The second method is somewhat similar to Clover, such as:
package com.runoob {
class HelloWorld
}
Second, you can define multiple packages in one file.
Quote
Scala usage import
keyword references the package.
Import java. awt. Color//Import Color
Import java. awt. _// Introduce all members within the package
Def handler (evt: event. ActionEvent) {//java. awt. event. ActionEvent
...//Because of the introduction of java. awt, the previous section can be omitted
}
import
statements can appear anywhere, not only at the top of the file. import
the effect extends from the beginning to the end of the statement block. This can significantly reduce the possibility of name conflicts.
If you want to introduce several members of the package, you can use the selector
(selector):
import java.awt.{Color, Font}
// Rename Members
import java.util.{HashMap => JavaHashMap}
// Hide Members
import java.util.{HashMap => _, _} // All members of the util package were introduced, but HashMap was hidden
Note: by default, Scala always introduces java.lang.\_
、 scala.\_
and Predef._
, this can also explain why packages that start with scala.
are often omitted when using them.