Scala Quick Learning Notes (i): variable functions, operators, basic types

Source: Internet
Author: User

To use Spark, learn Scala first.

Reference Tutorial: Http://meetfp.com/zh/scala-basic

Online compilation: Http://meetfp.com/tryout

Other information: HTTP://SCALACHINA.COM/NODE/16 http://blog.csdn.net/mapdigit/article/details/21878083

Characteristics:

    • Scala is a purely object-oriented language, all objects: Unify primitive types and classes, and unify functions and operators.
    • Scala is also a functional language, which shows that functions are an object in Scala and can be used very naturally by higher-order functions.
    • Scala is a statically typed language, but because of its powerful type inference, there are not many places where you actually need to specify the type. While having the security and efficiency advantages of static and compiled languages, Scala is as convenient, flexible and concise as static languages like Ruby,python.

0. Environment configuration:

First Skip, use the online compilation.

    • The end of the line is the end of the statement, and if you want to enter more than one statement in a row, use a semicolon.
    • To cross a line of statements, you have to use parentheses, or put the operator at the end of an unfinished line, and it will be treated as a sign of the end of the statement bit.
Object HelloWorld {  def main (args:array[string]) {    println ("Hello, world!" )  }}

I. Variable function

1. Variables: Var, val--immutable

    • Scala's variables are divided into two types, Var and val. var, or variable, is similar to the variables we touch in other languages such as Java, and Val, is value, similar to the non-assignable constants we use in other languages, or the final variable. Scala emphasizes the concept of immutable (immutable).
    • The Scala compiler infers the data type through type inference, or explicitly specifies the type of the variable, separated by a colon (:) after the name of the variable inference.
Int =5

2. Functions (function), procedure (procedure)

    • As you can see from the code above, the function definition starts with DEF, then the function name, followed by the argument list of the function in parentheses, separated by commas. Unlike Java or C, the type of the parameter appears after the parameter name, separated from the parameter name Colon. The type of the function (that is, the type of the return value) is separated by a colon after the argument list. After the function type, it is the equal sign "=" and then the body of the function surrounded by curly braces. The function return type can be omitted because the compiler can infer it. However, for the readability of the code, the return type should be noted as much as possible, and it can be omitted only if the code is very short and can see the return type at a glance.
def add (X:int, y:int): Int = {  + y}println ("2 + 3 =" + Add (2,3))
    • The purpose of the process is to have some kind of "side effect", rather than to get the results calculated. As mentioned above, a procedure is just a special function, specifically a function that has no return value, or that returns a unit of type.
def sayhito (name:string) {  println ("Hi," + name)}sayhito ("Nini")

PS: (1) named parameter allows you to specify the parameter name when the parameter is passed, so that the position of the argument is no longer important.

AddUser (name = "Tim", phone = "702-201-2345", age = 33)

(2) Default parameters, same as other languages.

(3) Repeat parameter, there is a ' * ' after the type, which means that the parameter can be repeated indefinite number of times, including 0. When the number of arguments is not 0 o'clock, the repeating parameter is actually an array inside. It is similar to array when used, except that a direct array cannot be passed in when called. If you need to pass the entire array (or another type of sequence), there is a workaround, that is, add a ' _* ' symbol, which is separated from the parameter by a comma, for example log(array: _*) .

def log (msgs:string*) = {  println (msgs.getClass.getName)  println (msgs.mkstring (","))}log () Log ("One", "one", "one", "three" = Array ("One", "one", "three")//log (array)//  above line wouldn ' t compile, type mismatch, expected Stringlog (array: _*)

II. operator

    • Scala has no operators, and there are no expressions in the usual sense. is actually a method (function), called the operator notation. such as 1+2 and 1.+ (2)
    • There are few operators that can do the prefix, only four: +,-,!,~. In addition, the prefix expressions are somewhat special, and their methods need to precede the corresponding operators with Unary_, for example unary_! , or unary_- .
    • Because the operator is essentially a method, you can overload the operator with the method overload.
    • Common operators and precedence are similar to C + +, not detailed.

      */% +-: =! < > & ^ |

    • Operators ending with ': ' are right-associative, and other operators are left-associative.

III. Basic Types

In Scala, the basic type is also class, for example, int type, from Scala. Int, every number, is Scala. An instance of Int. Boxing (boxing) and unboxing (unboxing) operations are transparent, and programmers do not need to be concerned (in fact, this is done by implicit conversions defined in predef).

1. Numeric type

    • Boolean:true or False
    • Byte:8 bit, signed (2-7 ~ 27-1)
    • Short:16 bit, signed (2-15 ~ 215-1)
    • Int:32 bit, signed (2-31 ~ 231-1)
    • Long:64 bit, signed (2-63 ~ 263-1)
    • Char:16 bit, unsigned (0 ~ 216-1)
    • Float:32 bit, single-precision floating-point number
    • Double:64 bit, double-precision floating-point number

Each basic type has a corresponding rich wrapper class. The basic type, when necessary, is converted to the corresponding rich wrapper class by an implicit conversion, thus invoking the method provided by the rich wrapper class.

= 2 Max 3println ("2 max 3 =" +=-1. ABSPRINTLN (" -1.abs =" += 1 to 5println (" 1 to 5 = "+= 1." Isvalidcharprintln ("1.isValidChar ="+ =-1. ISVALIDCHARPRINTLN ("-1. Isvalidchar = "+ N5)

The string in 2.Scala is a string that borrows directly from Java. However, since string is actually a series of immutable collections of char, most of the operations for collections in Scala can be used in string, specifically, These methods of string exist in the class Scala.collection.immutable.StringOps. Because the string can be implicitly converted to stringops when needed, there is no need for any additional conversions, which can be used by string.

// "Heo"println ("\" Hello\ ". Filter (_! = ' l ') =" + R3)

Like Java or C #, a string is immutable, and a string is manipulated to get a new string instance. Therefore, use StringBuilder if you need to operate a string frequently.

New stringbuilderbuilder.append ("Hello") builder.append (", World"+ = '! ') Builder.insert (0, "Me:") println (builder)    // Me:hello, world!

3. Literal constants: Same as Java. XML extensions. Function constants.

Val fun =new  function2[int, int, int.] {  = x += Fun (2,4) println ("Result =" + r Esult) Result

In 4.Scala, all values are class objects, and all classes, including value types, eventually inherit from a uniform root type any. The unified type is another feature of Scala. More specifically, Scala also defines several underlying classes (Bottom class), such as null and nothing.

    • Null is a subtype of all reference types, and nothing is a subtype of all types. The null class has only one instance object, NULL, similar to a null reference in Java. Null can be assigned to any reference type, but cannot be assigned to a value type.
    • Nothing, which can be used as the return type of a method without a normal return value, is very intuitive to tell you that this method does not return normally, and because nothing is a subclass of any other type, he can also be compatible with methods that require return values.
    • The unit type is used to identify a procedure, that is, a function that does not have a definite return value. This shows that the unit is similar to void in Java. The unit has only one instance, () and this instance has no real meaning.

Scala Quick Learning Notes (i): variable functions, operators, basic types

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.