Latest web development tutorials

Scala basic grammar

If you are a Java programmer before, and learn the basics of Java language, so you can quickly learn the basic grammar Scala.

Scala and Java the biggest difference is: Scala semicolon at the end of the statement; is optional.

We can think of Scala program is a collection of objects by each method call to implement messaging. Next we come to understand, the class, the concept of objects, methods, instance variables:

  • Objects - objects have properties and behaviors.For example: a dog-like attributes: color, name, behavior: call, run, eat and so on. Object is an instance of a class.

  • Class - class is an abstract object, and the object is a specific instance of a class.

  • Method - the method described in the basic act, a class can contain multiple methods.

  • Fields - Each object has its own unique set of instance variables, namely fields.Properties of the object through the field assignment to be created.


The first Scala program

Interactive Programming

Interactive programming not need to create a script file, you can call 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 file to execute code, HelloWorld.scala code as follows:

object HelloWorld {
   /* 这是我的第一个 Scala 程序
    * 以下程序将输出'Hello World!' 
    */
   def main(args: Array[String]) {
      println("Hello, world!") // 输出 Hello World
   }
}

Next we use scalac command to compile it:

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

After compiling, we can see the directories created under HelloWorld.class file that can run on Java Virtual Machine (JVM) on.

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

$ scala HelloWorld
Hello, world!
Online examples >>

The basic syntax

Scala basic syntax, note the following:

  • Case-sensitive - Scala is case-sensitive, which means logo Hello hello and have different meanings in Scala.

  • Class name - for all the class name first letter should be capitalized.

    If you need to use a few words to constitute a class name, the first letter of each word capitalized.

    Example: class MyFirstScalaClass

  • Method name - the first letter of all methods lowercase names.

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

    Example: def myMethodName ()

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

    When you save a file, it should save the object name to use (remember Scala is case-sensitive), and append ".scala" file extension. (If the file name and object names do not match, the program will not compile).

    Example: Let's say "HelloWorld" is the name of the object. Then the file should be saved as' HelloWorld.scala "

  • def main (args: Array [String ]) - Scala program from main () method begins processing, which is a mandatory part of each program entry Scala program.


Identifiers

Scala can use two forms of identifiers, digital characters and symbols.

Alphanumeric use start with a letter or underscore can be followed by the letter or number, a symbol "$" in Scala is also seen as letters. However, using the identifier, the application to "$" at the beginning of the identifier is reserved Scala compiler should avoid using the "$" Start identifier to avoid conflict.

Scala and Java naming convention using a similar naming camel, the first character lowercase, such as toString. The first character class names or uppercase. In addition it should be avoided in order to underscore the end of the identifier to avoid collisions. Symbol identifier comprises one or more symbols, such as +,:?, Etc., such as:

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

It will use the escaped identifier when Scala internal implementation, such as: -> Use $ colon $ minus $ greater to represent the symbol. So if you need to access Java code: -> method, you need to use Scala's internal name $ colon $ minus $ greater.

Mixed alphanumeric identifier from the identifier later followed by one or more symbols, such as the Scala unary_ + name + method for internal implementation time. Literal identifier for the string "is defined, for example` x` `yield`.

You can use any valid Scala identifier in between ", Scala will be interpreted as a Scala identifier, a typical use for the Thread of the yield method, in Scala you can not use Thread.yield () is because the yield of Scala keywords, you must use Thread.`yield` () to use this method.


Scala keywords

The following table lists the scala reserved keywords, we can not 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 comment

Scala is similar to many Java supports single-line comments. Multi-line comments can be nested, but must be properly nested, a comment that begins with a symbol corresponding to end symbol. NOTE Scala compiler will be ignored, examples are as follows:

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

Blank lines and spaces

Only one line with a space or comments, Scala will think it is a blank line, it will ignore it. Marks can be spaces or comments to split.


Newline

Scala is a line-oriented language, the statement with a semicolon (;) end or line breaks. Scala program, the semicolon at the end of the statement is usually optional. If you are willing to enter one, but if there is only one line in the statement or not write. On the other hand, if you write multiple statements in a row so the semicolon is needed. E.g

val s = "本教程"; println(s)

Scala package

Custom packages

Scala is defined using the keyword package package, in Scala code to define a package in two ways:

The first method, and Java, as in the file header defines the package name, this method follow all codes are placed in the newspaper. such as:

package com.w3big
class HelloWorld

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

package com.w3big {
  class HelloWorld 
}

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

Quote

Scala using import keyword reference package.

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. import results from extending to the end of the statement block. This can significantly reduce the likelihood of name conflicts.

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

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

Note: By default, Scala always introduced java.lang._, scala._ and Predef._, Here you can also explain why the scala head of the packet, when using the scala are omitted.