[Scala Tours]2-Basics-Tour of Scala

Source: Internet
Author: User
Tags traits
On this page, we'll cover the basics of Scala.

Try Scala in the browser

You can run Scala from the Scalafiddle in the browser.

    1. Open Https://scalafiddle.io

    2. In the left pane, pasteprintln("Hello, world!")

    3. Click the "Run" button. The output is displayed in the right pane.

This is a simple, 0-setting way to test Scala code snippets.

An expression

An expression is a statement that can be evaluated.

1 + 1

You can use println the result of an output expression.

println (1)//1PRINTLN (1 + 1)//2println ("hello!")//Hello!println ("Hello," + "world!")//Hello, world!

Value

You can use val keywords to name the result of an expression.

Val x = 1 + 1println (x)//2

Named results, such as here x , are called values. Referencing a value does not recalculate it.

Values cannot be reassigned.

Val x = 1 + 1x = 3//This does not compile.

The compiler can infer the value of a type, but you can also explicitly declare a type, as follows:

Val x:int = 1 + 1

Note that the type declaration Int x occurs after the identifier, and you also need to add one between the two : .

Variable

Variables are like values, but you can reassign them. You can use var keywords to define a variable.

var x = 1 + 1x = 3//This compiles because "x" are declared with the "var" keyword.println (x * x)//9

As with values, you can explicitly declare types:

var x:int = 1 + 1

code block

You can combine the expressions around them. We call this a block of code.

The result of the last expression of the block is also the result of the entire block.

println ({  val x = 1 + 1  x + 1})//3

Function

The function is an expression with parameters.

You can define an anonymous function (that is, no name), which returns a given integer + 1:

(x:int) = x + 1

On the => left side of the eject symbol is a list of parameters. On the right is an expression that contains a parameter.

You can also name the function.

Val AddOne = (x:int) + x + 1println (AddOne (1))//2

A function can use more than one parameter.

Val add = (x:int, Y:int) = x + yprintln (Add (1, 2))//3

Or it does not require parameters.

Val GetTheAnswer = () = 42println (GetTheAnswer ())//42

Method

Methods look very similar to functions, but there are some key differences between them.

method uses the def keyword definition. defThe following is the method name, the argument list, a return type, and a principal.

def add (X:int, y:int): Int = x + yprintln (Add (1, 2))//3

Note that the return type is declared after the argument list and colon : Int .

Method can use multiple parameter lists.

def addthenmultiply (X:int, Y:int) (multiplier:int): Int = (x + y) * MULTIPLIERPRINTLN (addthenmultiply (1, 2) (3))//9

Or there is no parameter list at all.

def name:string = System.getproperty ("name") println ("Hello," + name + "!")

There are some other differences, but now you can think of them as something similar to a function.

Methods can also have multiple-line expressions.

def getsquarestring (input:double): String = {  val square = input * input  square.tostring}

bodyThe last expression is the return value of the method. (Scala has a return keyword return , but it's rarely used.) )

Class

You can use the Class keyword to class define a class, and then use its name and constructor parameters.

Class Greeter (prefix:string, suffix:string) {  def greet (name:string): Unit =    println (prefix + name + suffix)}

The greet return type of the method is Unit , which means that the return has no meaning. It is similar to keywords in Java and C void (except that because each Scala expression must have a certain value, there is actually a type Unit of singleton value, written as () . It does not carry any information. )

You can use keywords new to create an instance of a class.

Val greeter = new Greeter ("Hello,", "!") Greeter.greet ("Scala developer")//Hello, Scala developer!

We'll describe the class in more detail later.

Sample class

Scala has a special type of class, called the "sample" class. By default, the sample class is immutable and is compared by value.

You can case class define a sample class with a keyword.

Case class Point (X:int, Y:int)

You may not need to new instantiate the sample class with keywords.

Val point = Point (1, 2) Val anotherpoint = Point (1, 2) Val yetanotherpoint = Point (2, 2)

They are compared by value.

if (point = = Anotherpoint) {  println (point + "and" + Anotherpoint + "is the same.")} else {  println (point + "and" + Anotherpoint + "is different.")} Point (at) and Point (Same.if) is the (point = = Yetanotherpoint) {  println (point + "and" + Yetanotherpoint + "is the same.")} else {   println (point + "and" + Yetanotherpoint + "is different.")} Point (2,2) is different.

We want to introduce a lot of sample classes, we believe you will love them! We'll cover them in more detail later.

Object

Objects are individual instances of their own definition. You can think of them as a single example of their own class.

You can define objects by using keywords object .

Object Idfactory {    private var counter = 0   def create (): Int = {     counter + = 1        counter  }}

You can access an object by referencing the object name.

Val newid:int = Idfactory.create () println (newId)//1val Newerid:int = Idfactory.create () println (Newerid)//2

We'll cover the objects in more detail later.

Characteristics

A feature is a type that contains some fields and methods. Multiple features can be grouped together.

You can define traits by using keywords trait .

Trait Greeter {   def greet (name:string): Unit}

The feature can also have a default implementation.

Trait Greeter {  def greet (name:string): Unit =     println ("Hello," + name + "!")}

You can use extends the keyword extension feature and use the override keyword overlay implementation.

Class Defaultgreeter extends Greeterclass customizablegreeter (prefix:string, postfix:string) extends Greeter {   Override def greet (name:string): Unit = {        println (prefix + name + postfix)  }}val greeter = new Defaultgreeter () GR Eeter.greet ("Scala developer")//Hello, Scala developer!val customgreeter = new Customizablegreeter ("How is You,", "?") ) Customgreeter.greet ("Scala developer")//How is you, Scala developer?

Here, DefaultGreeter only a single trait is extended, but it can extend multiple traits.

We will describe the traits in more detail later.

Main method

The Main method is the entry point for a program. The Java Virtual machine requires a main master method named, and accepts a parameter, an array of strings.

With objects, you can define a main method, as follows:

Object Main {    def main (args:array[string]): Unit =     println ("Hello, Scala developer!")}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.