Getting Started with Scala basics-1

Source: Internet
Author: User

The first step is to build the Scala development environment and find tutorials on the web.

declaring constants and variables
val foo = 0  //constant var bar = 0  //variable

  

In Scala, it is more encouraged to declare using Val, which is the recommended constant. Most of the time do not need a semicolon, look at their own good ... Although it is a strongly static type of language, it does not write the type-this is type inference.

You can also specify a type:

Val spark:string = "Hello Scala"

  

Multiple simultaneous declarations:

Val Xint, Yint = +  //Xint, yint all declared as 100

  

Common Types

Like Java, there are classes that represent numeric types in Scala, but Scala does not differentiate between primitive types and reference types. That means everything in Scala is an object.

Scala adds a number of functional enhancements to the functionality of numeric types in Java, which involves implicit conversions. For example, the string type is converted to the Stringops type. There are richint, richdouble, etc. corresponding to the int, double type. As for any new method, you can view the Scala API.

operator

The arithmetic operator should be no different from what is expected, because if there is a difference it will be troublesome. But the arithmetic operator is actually a method.

A + b  equals  a.+ (b)

This can usually be simplified for a method with an implicit parameter and an explicit parameter. Such as:

1.to  This produces a 1-10 range instance, which is equivalent to 1 to  10

Choice of two styles.

Scala does not offer + + and – (don't think I've got the wrong number, here are two-numbers). These are common operators in two other languages because it is not worth adding an extra special case for less pressing a key.

Operators can be overloaded in Scala.

calling functions and methods

Functions (function) and methods (method)

Once the corresponding package is introduced, it is simple to use the function, and no static method needs to be called from a class.

MATH.SQRT (2)  is equivalent to  scala.math.sqrt (2)  //The package name that begins with Scala, which can be omitted.

  

There are no static methods in Scala, but concepts such as singleton objects and associated objects can achieve similar characteristics, which are described later.

Bigint.probableprime (util. Random)

  

Typically, no parentheses are used when you use a method that has no parameters and does not change the current object.

Apply Method

S is a string, andS(4) will return the 4th character in the string. In the use of shapes such asS(4This, like the syntax of a function call, actually calls theapply() method. In other words, s(4) equals s. Apply(4)

Two easily confusing concepts-expressions (expression) and statements (statement). The expression has a value, and the statement does not have a value to perform the operation only.

The reason for this is that in Scala, almost all constructed grammatical structures have values, that is, expressions. This can make the program more streamlined and readable.

For example, if an expression is a value, the statement block is also a value, and the value of the last expression.

There is a type unit in the corresponding Java Void,scala, which is used to denote "no useful value" (void means no value, there is still a difference).

Conditional Expressions

If/else expressions are valuable in Scala, except for this, which is no different from languages like Java. The effect of a value can be as follows:

Val s = if (x > 0) 1 else-1//is equivalent to the other way of writing if (X > 0) s = 1 else s =-1

  

The first notation can be used to initialize a Val, while the second requires S to be var. As I said earlier, the use of Val is more encouraged in Scala.

At the same time, this conditional expression can also be achieved than the three-mesh operator? : more flexible features.

If the types on both sides of the IF and else are different, such as:

if (x > 0) "Positive" else-1

  

The returned type will be a public super-type of two branch types (here is the public super-type any of string and int).

If there is no else part, then the if expression might not return a value, which would require the unit type mentioned earlier, write ().

if (x > 0) 1//This is equivalent to the else part returning the unit type, equivalent to the following notation if (x > 0) 1 Else ()

  

Statement Termination

Semicolons are not required, but using them does not cause harm.

There is no need to use semicolons to determine where the end of a statement is based on context. How to judge whether the end of the sentence, later in the coding process will slowly accumulate feeling.

If you need to write multiple statements in a single line, you need to use a semicolon. When writing a longer statement, if you need to write in a branch, make sure that the front end of the line needs to be terminated with a symbol that cannot be used at the end of the statement. For example, like the following operator:

A = S0 + (v-v0) * t +//+ shows that this is not the end of the statement Oh  0.5 + (a-a0) * t * t//The following is a problem. A = S0 + (v-v0) * t  + 0.5 + (a-a 0) * t * t

  

It can also be found that Scala recommends using two spaces to indent.

Scala programmers are more inclined to use Kernighan & Ritchie-style curly braces (the recommended method in Java) because of the need to judge the termination of a statement:

if (n > 0) {  R = R * N  n = 1}

  

block expressions and Assignments

In Scala, {} contains a series of expressions, and {} finally returns an expression-the last expression.

The value of the assignment statement, however, is the unit type. This also largely determines the assignment statements that appear in Java and C + + with x = y = 1, which is almost impossible to appear in Scala.

Input and Output

Input function:  readline ( Readint

In the output section, it is common for print(), println(), and printf().

Loops

Look at the For loop in Scala:

for (i <-expression)  //Let I traverse all values of the expression, the execution of the traversal depends on the type of expression//example for (I <-1  to N)//traverse 1 to nfor (i <-0 util S.leng TH)  //Traverse 0 to s.length-1//traversal sum var = 0for (ch <-"Hello") sum + = ch

  

In fact, Scala is more of a function rather than an instruction style to traverse such operations. I'll see you in the back.

advanced for Loop and for-deduction

Use multiple "generator" (generators) in A For loop:

for (I <-1 to 3, J <-1 to 3) print ((Ten * I +j) + ""//Result: 11 12 13 21 22 23 31 32 33

  

Use "Filter" (Filter, Guard) in the For loop to filter out some of the non-conforming enumeration conditions:

for (I <-1 to 3; J <-1 to 3 if I! = j) Print ((Ten * i + j) + "")//Result: 12 13 21 23 31 32

  

Multiple filter can be used, with semicolons separated in the middle.

You can use any number of definitions in the for expression to introduce the use of variables in loops:

for (I <-1 to 3, from = 4-i, J <-from to 3) print ((Ten * i + j) + "")//Results: 13 22 23 31 32 33

  

If the loop body of the for expression starts with the yield keyword, the loop constructs a collection, which is called a for deduction. The derived collection is type-compatible with the first generator.

for (c <-"Hello"; I <-0 to 1) yield (c + i). tochar//generate "Hieflmlmop"

  

You can also replace the parentheses of the for expression with curly braces, which eliminates the effort to write semicolons.

The for expression has a lot of content, and this is not all. There are some high-level discussions in the programming in Scala, and here's a little bit of a first entry.

function

There is no concept of functions in Java, and functions are implemented using static methods.

Definition of the function:

def function name (parameter of the specified type): Optional return value type = function Body def FAC (n:int) = {  var R = 1 for  (i <-1 to n) R = R * I  R}

  

As long as the function is not recursive, you do not need to give the return value type of the function (because there is type inference). A recursive function needs to be written as follows:

def FAC (n:int): Int = if (n <= 0) 1 Else n * FAC (N-1)

  

In Scala, returns are not often used to return values.

default parameters and named parameters

There seems to be no default parameters and named parameters in Java, at least I have never used them. But remember C + + is there.

def decorate (str:string, left:string = "[", right:string = "]") = left  + str + Right

  

The above function has two parameters with default values left and right. If these two parameters are not given, the default value is used to call this function. You can also give your own parameters instead of the default.

When the number of arguments is insufficient, the default parameters will be used from the forward.

When calling a function, if you specify a parameter name, the parameter can be not in the order of the argument list:

Decorate ("Hello", right = "]<<<")

You can also know from above that you can mix unnamed and named parameters.

variable length parameter
def sum (args:int*) = {  var result = 0 for  (arg <-args) result + = arg  result}

  

An asterisk indicates an acceptable variable-length parameter list. The parameters that the function actually gets are the SEQ type.

However, when you invoke a variable-length parameter function, you cannot directly use a SEQ-type parameter. To break a SEQ type into a single parameter sequence, use : _*.

def recursivesum (args:int*) = {  if (args.length = = 0) 0  else Args.head + recursivesum (args.tail: _*)}

  

Process (Procedure)

The definition of a procedure is similar to a function. The function body is in curly braces, and there is no = sign before the curly brace, the return value is the unit type, and this is the process. (You can also write the = sign and indicate that the return value is a unit type to define the procedure.) )

Typically, a procedure does not return a value, only a procedure is called for a side effect.

Lazy Value

When Val is declared as lazy, initialization is deferred until it is first evaluated.

Lazy val words = io. Source.fromfile ("/usr/share/dict/words"). mkstring

  

If the program has always asked words, then Scala will not open that file. The file is opened when you actually use words for the first time.

Lazy values are useful for expensive initialization statements and can handle some initialization problems such as cyclic dependencies. Or the basis for developing lazy data structures.

You can think of lazy values as being in the middle of the Val and Def states:

    • Val is evaluated when it is defined
    • Lazy Val is evaluated on first use
    • DEF is valued every time it is used
Exception

The exception mechanism in Scala is the same as in Java and C + +. However, there is no exception to be examined in Scala, that is, there is no need to explain what exception the function method might throw.

Use throw to throw an exception. The type of the throw expression is nothing.

Catching Exceptions:

try {   process (new URL ("Http://horstmann.com/fred-tiny.gif")} catch {case  _: = = Malformedurlexception = > println ("Bad URL:" + URL) case  ex:ioexception = Ex.printstacktrace ()}

  

If you do not need to use the caught exception object, use _ instead of the variable name (_ is a wildcard character in Scala).

There are also try/finally statements, usually used to clean up. Can be combined into try/catch/finally statements

from:http://nerd-is.in/2013-08/scala-learning-control-structures-and-functions/

  

  

Getting Started with Scala basics-1

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.